服务器端程序,利用DatagramSocket负责监听端口,当客户端发过来消息时,服务器端就会响应,并将消息内容保存到Datagrampacket对象中,并且!每一次while循环必须重新创建DatagramPacket对象用于保存消息数据。并将socket,packet对象发送给子线程,由子线程完成后面的事务,主线程将进行下一次循环,在receive(packet)处阻塞监听客户端的响应。
package UDPSocketTell;
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
public class UDPServerThreadText {
public static void main(String[] args) throws IOException {
// TODO Auto-generated method stub
DatagramSocket socket = new DatagramSocket(8899);
byte[] infoBytes = new byte[1024];
int num = 0;
System.out.println("服务器端启动了·········");
while (true) {
DatagramPacket packet = new DatagramPacket(infoBytes, infoBytes.length);
socket.receive(packet);
UdpServerThread thread = new UdpServerThread(packet, socket, infoBytes);