public class TestServer implements Runnable{
private DatagramSocket server;
private String person;
public TestServer(int port){
// this.person = person;
try {
server = new DatagramSocket(port);
} catch (SocketException e) {
e.printStackTrace();
}
}
@Override
public void run() {
while (true){
byte[] b = new byte[1024*60];
DatagramPacket packet = new DatagramPacket(b, 0, b.length);
try {
server.receive(packet);
byte[] datas = packet.getData();
int len = packet.getLength();
String data = new String(datas, 0 , len);
if (data.equals("bye")){
break;//退出
}
} catch (IOException e) {
e.printStackTrace();
}
}
server.close();
}
// 创建 准备包裹 接收 分析 释放
public static void main(String[] args) throws IOException {
System.out.println("老师端启动");
new Thread(new TestServer(8888)).start();
}
}
服务器端启动没问题
客户端(使用Idea和Eclipse)启动不了
客户端代码如下:
public class TestClient implements Runnable {
private DatagramSocket client;
private BufferedReader br;
private String toIP;//对方IP
private int toPort;
public TestClient(int port, String toIP, int toPort) {
this.toIP = toIP;
this.toPort = toPort;
try {
client = new DatagramSocket(port);
br = new BufferedReader(new InputStreamReader(System.in));
} catch (SocketException e) {
e.printStackTrace();
}
}
@Override
public void run() {
while (true) {
String data;
try {
data = br.readLine();
byte[] datas = data.getBytes();
DatagramPacket packet = new DatagramPacket(datas, 0, datas.length,
new InetSocketAddress(this.toIP, this.toPort));
client.send(packet);
if (data.equals("bye")) {
break;
}
} catch (IOException e) {
e.printStackTrace();
}
}
client.close();
}
// 创建 准备数据 打包 发送 释放
public static void main(String[] args) throws IOException {
System.out.println("学生端启动");
new Thread(new TestClient(8000, "localhost", 8888));
}}
使用debug运行客户端出现:
经过排查问题出现这里,后面忘了加start():
然后又遇到学生端打印的数据没有出现在老师端,最后发现服务端的run()里面没有加打印语句,把数据打印出来》》引以为戒