JAVA网络编程之基于UDP的服务器端和客户端的简单实现

用户数据包协议(英语:User Datagram Protocol,缩写为UDP),又称用户数据报文协议,是一个简单的面向数据报的传输层协议,正式规范为RFC 768。

在TCP/IP模型中,UDP为网络层以上和应用层以下提供了一个简单的接口。UDP只提供数据的不可靠传递,它一旦把应用程序发给网络层的数据发送出去,就不保留数据备份(所以UDP有时候也被认为是不可靠的数据报协议)。UDP在IP数据报的头部仅仅加入了复用和数据校验(字段)。

DatagramSocket类:在UDP中没有明显的客户端类和服务器端类,客户端既可以发消息也可以接受消息。均在创建的过程会有SocketException异常。

DatagramPacket类:对于接受数据,将接受到的数据存储到DatagramPacket,然后从该对象中读取数据。对于发送数据,将发送的数据先存到DatagramPacket中,然后将该对象发送。

UDP服务器端实现

package com.xieyincai.net;

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

public class SimpleUDPServer {

	private final static int PORT = 8000;
	
	public static void main(String[] args) {
		// TODO Auto-generated method stub

		DatagramSocket datagramSocket = null;
		
		try {
			// Constructs a datagram socket and binds it to the specified port on the local host machine.
			datagramSocket = new DatagramSocket(PORT);
			
			while(true) {
				try {
					DatagramPacket request = new DatagramPacket(new byte[4096], 4096);
					datagramSocket.receive(request);
					
					String result = new String(request.getData(), 0, request.getLength(), "UTF-8");
					byte[] data = ("ECHO:\t" + result).getBytes("UTF-8");
					
					DatagramPacket response = new DatagramPacket(data, data.length, request.getAddress(), request.getPort());					
					datagramSocket.send(response);
					
					System.out.println("CLIENT:\t" + request.getAddress() +" : " + request.getPort() + "\t" + result);
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}

		} catch (SocketException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} finally {
			datagramSocket.close();
		}
	}

}

UDP客户端实现

package com.xieyincai.net;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;
import java.net.UnknownHostException;

public class SimpleUDPClient {

	private final static String HOSTNAME = "localhost";
	private final static int PORT = 8000;
		
	public static void main(String[] args) {
		// TODO Auto-generated method stub

		DatagramSocket datagramSocket = null;
		
		try {
			// Constructs a datagram socket and binds it to any available port on the local host machine.
			datagramSocket = new DatagramSocket();
			InetAddress address = InetAddress.getByName(HOSTNAME);
			
			String hello = String.valueOf(System.nanoTime());
			
			System.out.println(hello);
			
			byte[] data = hello.getBytes("UTF-8");
			
			DatagramPacket request = new DatagramPacket(data, data.length, address, PORT);
			DatagramPacket response = new DatagramPacket(new byte[4096], 4096);
			
			datagramSocket.send(request);
			datagramSocket.receive(response);
			
			String result = new String(response.getData(), 0, response.getLength(), "UTF-8");
			
			System.out.println(result);
			
		} catch (UnknownHostException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (SocketException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} finally {
			datagramSocket.close();
		}
	}

}

服务器端输出:

CLIENT:	/127.0.0.1 : 53420	4022384637513234
CLIENT:	/127.0.0.1 : 53424	4022390644392011
CLIENT:	/127.0.0.1 : 53427	4022392924054045

客户端输出:

4022392924054045
ECHO:	4022392924054045

Leave a Reply

Your email address will not be published. Required fields are marked *