用线程实现多用户通信出现奇怪的问题,麻烦大家帮忙看看
public class DatagramServer { public static void main(String[] args) { try { //1.创建DatagramSocket,指定端口 DatagramSocket socket = new DatagramSocket(8787); System.out.println("我是服务器,我已经准备好了!"); //3.接收客户端发送的信息(此方法在接收数据包之前会一直阻塞) int count = 0; byte[] buf = new byte[1024]; //2.创建DatagramPacket,用于接收客户端发送的数据 //》》》》》下面这一句放在while循环之外就出现了奇怪的运行结果,见图 DatagramPacket p = new DatagramPacket(buf, buf.length); while(true){ socket.receive(p); ServerThread s = new ServerThread(socket, p, buf); s.start(); System.out.println("当前请求的客户机有"+ (++count) +"台"); } } catch (SocketException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } public class ServerThread extends Thread{ DatagramSocket socket1 = null; DatagramPacket p = null; byte[] buf = null; public ServerThread(DatagramSocket socket1, DatagramPacket p, byte[] buf){ this.socket1 = socket1; this.p = p; this.buf = buf; } @Override public void run() { String info = null; InetAddress address = null; int port = 0; byte[] buf1 = null; DatagramPacket p1 = null; info = new String(buf, 0, p.getLength()); System.out.println("客户端对我说:"+info); address = p.getAddress(); port = p.getPort(); String reply = "欢迎您!"; buf1 = reply.getBytes(); p1 = new DatagramPacket(buf1, buf1.length, address, port); try { socket1.send(p1); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }
如上代码:如果服务器端的DatagramPacket p = new DatagramPacket(buf, buf.length);
这一句放在while循环之外,则整个程序的运行结果如下,我就想知道为什么第一次的数据报文服务器不能接收到呢?(正确的程序代码应该是放到while循环里,因为每一次接收到的是不同的报文。)
感觉第一次的数据报文丢了一样