Java TCPIP之UDP 服务器端

package network;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;

public class UDPEchoServer {

	private static final int ECHOMAX = 255;

	public static void main(String[] args) throws IOException {
		if (args.length != 1) {

			throw new IllegalArgumentException("Parameter(s): <Port>");
		}

		int servPort = Integer.parseInt(args[0]);

		DatagramSocket socket = new DatagramSocket(servPort);
		DatagramPacket packet = new DatagramPacket(new byte[ECHOMAX], ECHOMAX);

		while (true) { // Run forever, receiving and echoing datagrams
			socket.receive(packet); // Receive packet from client			
			System.out.println("Handling client at "
					+ packet.getAddress().getHostAddress() + " on port "
					+ packet.getPort());
			socket.send(packet); // Send the same packet back to client
			packet.setLength(ECHOMAX); // Reset length to avoid shrinking buffer
		}

	}
}


    UDP 服务器为所有的通信使用同一个套接字,这点与 TCP服务器不同,TCP服务器为每个成功返回的 accept()方法创建一个新的套接字。

    当我们接收数据报文时,将其地址和端口解释为源地址和端口,而在发送数据报文时,则将其地址和端口称为目的地址和端口。


你可能感兴趣的:(Java TCPIP之UDP 服务器端)