package duoxiancheng;
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.Socket;
import java.net.SocketException;
import java.util.Scanner;
//多线程聊天】
public class LiaoTian {
public static void main(String[] args) {
// TODO Auto-generated method stub
new Receive().start();
new Send().start();
}
}
class Receive extends Thread{
public void run(){
try {
DatagramSocket socket = new DatagramSocket(4444);
DatagramPacket packet = new DatagramPacket(new byte[1024],1024);
while(true){
socket.receive(packet);//接受
byte[] arr = packet.getData();//转为字节数组
int len = packet.getLength();//获取长度
String str = new String(arr,0,len);//转换为字符串
String ip = packet.getAddress().getHostAddress();//获取ip地址
int port = packet.getPort();//获取端口号
System.out.println(ip+":"+port+":"+str);//打印
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
class Send extends Thread{
public void run(){
Scanner sc = new Scanner(System.in);
try {
DatagramSocket socket = new DatagramSocket();
while(true){
String line = sc.nextLine();
if("quit".equals(line))
break;
DatagramPacket packet = new DatagramPacket(line.getBytes(),line.getBytes().length,InetAddress.getByName("127.0.0.1"), 4444);
socket.send(packet);//发送
//
}
socket.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
运行后是这样的
da
127.0.0.1:59677:da
ddddd
127.0.0.1:59677:ddddd
这里的端口号为什么不是我程序里面的4444呢? |