【求助】UDP多线程
想要实现多线程的话,服务器应该需要循环侦听等待客户端的连接吧?可是UDP的数据报如何像TCP的输入流那样,拥有一个终止的判断条件(while(...) != null)呢?如果没有终止条件,循环侦听就真正陷入死循环了……
想要实现多线程的话,服务器应该需要循环侦听等待客户端的连接吧?可是UDP的数据报如何像TCP的输入流那样,拥有一个终止的判断条件(while(...) != null)呢?如果没有终止条件,循环侦听就真正陷入死循环了……
2015-09-06
UDPServer.java //服务端 ======================================== package UDP; import java.net.DatagramPacket; import java.net.DatagramSocket; public class UDPServe { public static void main(String[] args) { try { DatagramSocket socket = new DatagramSocket(9099); System.out.println("Serve is waiting..."); byte[] data = null; DatagramPacket packet = null; while (true) { data = new byte[1024]; packet = new DatagramPacket(data, data.length); socket.receive(packet); UDPServeThread thread = new UDPServeThread(socket, data, packet); thread.start(); } // socket.receive(packet); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } } } UDPServerThread.java //服务线程 package UDP; import java.net.DatagramPacket; import java.net.DatagramSocket; import java.net.InetAddress; public class UDPServeThread extends Thread { DatagramSocket socket = null; byte[] data = null; DatagramPacket packet = null; public UDPServeThread(DatagramSocket socket, byte[] data, DatagramPacket packet) { this.data = data; this.socket = socket; this.packet = packet; } @Override public void run() { try { System.out.println("Serve is waiting...3"); String info = new String(data, 0, packet.getLength()); System.out.println("Receive Client " + info); // 响应数据 InetAddress address = packet.getAddress(); int port = packet.getPort(); byte[] dataReply = "welcome".getBytes(); DatagramPacket packetReply = new DatagramPacket(dataReply, dataReply.length, address, port); socket.send(packetReply); } catch (Exception e) { e.printStackTrace(); }finally{ // socket.close(); } super.run(); } }
举报