发送方,接收方
package Chat;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetSocketAddress;
public class Talksend implements Runnable{
DatagramSocket socket = null;
BufferedReader reader = null;
private int fromPort;
private String toIP;
private int toPort;
public Talksend(int fromPort, String toIP, int toPort) {
this.fromPort = fromPort;
this.toIP = toIP;
this.toPort = toPort;
try{
socket = new DatagramSocket(fromPort);
reader = new BufferedReader(new InputStreamReader(System.in));
}catch (Exception e){
e.printStackTrace();
}
}
@Override
public void run() {
//准备数据,控制台读取数据 system.in
while (true) {
try{
String data = reader.readLine();
byte[] datas = data.getBytes();
DatagramPacket packet = new DatagramPacket(datas, 0, datas.length, new InetSocketAddress(this.toIP,this.toPort));
socket.send(packet);
if (data.equals("bye")){
break;
}
}
catch (Exception e){
e.printStackTrace();
}
}
socket.close();
}
}
接收类
package Chat;
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.SocketException;
public class TalkReceive implements Runnable{
DatagramSocket socket = null;
private int port;
private String MsgFrom;
public TalkReceive(int port,String msgFrom) {
this.port = port;
this.MsgFrom = msgFrom;
try {
socket = new DatagramSocket(port);
} catch (SocketException e) {
throw new RuntimeException(e);
}
}
@Override
public void run() {
while (true){
try {
byte[] container = new byte[10];
DatagramPacket packet = new DatagramPacket(container,0,container.length);
socket.receive(packet);
byte[] data =packet.getData();
String receivedata = new String(data, 0, data.length);
System.out.println(MsgFrom+": "+receivedata);
if (receivedata.equals("bye")){
break;
}
} catch (IOException e) {
throw new RuntimeException(e);
}
}
socket.close();
}
}
学生发消息,两个线程
package Chat;
public class TalkStudent {
public static void main(String[] args) {
//开启两个线程
new Thread(new Talksend(7777,"localhost",9911)).start();
new Thread(new TalkReceive(8822,"老师")).start();
}
}
老师发消息,两个线程
package Chat;标签:12,java,String,2022,import,new,多线程,public,socket From: https://www.cnblogs.com/RUI2022/p/16994915.html
public class TalkTeacher {
public static void main(String[] args) {
new Thread(new Talksend(5555,"localhost",8822)).start();
new Thread(new TalkReceive(9911,"学生")).start();
}
}