【代码积累】UDP server

import java.io.IOException;
import java.net.*;


public class UDPServer {
	public static final int LocalPort = 3000;
	public static final int RemotePort = 9000;
	
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		String str_send = "I am Server!";
		byte[] buf = new byte[1024];
		DatagramSocket dp_recvSock = null;
		InetAddress localAddress = null;
		InetAddress remoteAddress = null;
		
		//���������socket
		try {
			dp_recvSock = new DatagramSocket(LocalPort);
		} catch (SocketException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		try {
			localAddress = InetAddress.getLocalHost();
		} catch (UnknownHostException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}
		remoteAddress = localAddress;
		
		//�������ջ�����
		DatagramPacket dp_recv = new  DatagramPacket(buf,1024);
		
		System.out.println("Server is on,wating for client...");
		boolean isRunning = true;
		//ѭ���н���client����Ϣ��������Ӧ��
		while(isRunning)
		{
			try {
				dp_recvSock.receive(dp_recv);
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			
			//��ӡ�յ�����Ϣ
			System.out.println("Recv:\r\n"+new String(dp_recv.getData()));
			
			//����Ϣ��client
			DatagramPacket dp_send = new DatagramPacket(str_send.getBytes(), str_send.length(),remoteAddress,RemotePort);
			try {
				dp_recvSock.send(dp_send);
				isRunning = false;
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		dp_recvSock.close();
	}

}

你可能感兴趣的:(【代码积累】UDP server)