UDP 多线程
收到消息
public class ChatReceice implements Runnable{
DatagramSocket socket;
private String name;
private int potrIP;
public ChatReceice(int potrIP,String name){
this.name =name;
this.potrIP=potrIP;
try {
socket=new DatagramSocket(potrIP);
} catch (SocketException e) {
e.printStackTrace();
}
}
public void run() {
try {
while(true){
byte[] butter=new byte[2040];
DatagramPacket packet=new DatagramPacket(butter, 0,butter.length);
socket.receive(packet);
byte [] data =packet.getData();
String receivedata=new String(data,0,data.length);
if(receivedata.equals("Bye")){
socket.close();
break;
}
else{
System.out.println(this.name+":"+receivedata);
}
}
} catch (Exception e) {
e.printStackTrace();
}finally {
socket.close();
System.out.println("关闭了接口");
}
}
}
发送消息
public class ChatSends implements Runnable{
DatagramSocket socket ;
BufferedReader buffere;
DatagramPacket packet ;
private String toIP ;
private int toport;
private int fromIP;
public ChatSends(int toport,String toIp,int fromIP){
this.toIP=toIp;
this.toport=toport;
this.fromIP=fromIP;
try {
socket=new DatagramSocket(toport);
buffere=new BufferedReader(new InputStreamReader(System.in));
} catch (Exception e) {
e.printStackTrace();
}
}
public void run() {
while(true){
try {
String string=buffere.readLine();
byte [] data=string.getBytes();
packet= new DatagramPacket(data,0,data.length,new InetSocketAddress(this.toIP,this.fromIP));
socket.send(packet);
if(string.equals("Bye")){
break;
}
} catch (IOException e) {
e.printStackTrace();
}finally {
socket.close();
}
}
socket.close();
}
}
多线程
Student
public class ChatStudent {
public static void main(String[] args) {
new Thread(new ChatSends(1111,"127.0.0.1",3332)).start();
new Thread(new ChatReceice(8882, "老师")).start();
}
}
Teacher
public class ChatTeacher {
public static void main(String[] args) {
new Thread(new ChatSends(2222,"127.0.0.1",8882)).start();
new Thread(new ChatReceice(3332, "学生")).start();
}
}