UDP 通信

不使用任何框架,最基础的UDP通信。

TCP不保证消息边界,但UDP保证消息边界。所以不用考虑拆包、黏包问题。

1.UDPServer

java.net.DatagramSocket
代表UDP套接字。
java.net.DatagramSocket.DatagramSocket(int port) 

DatagramSocket的构造函数。

java.net.DatagramPacket

UDP的数据包。
java.net.DatagramPacket.DatagramPacket(byte[] buf, int length)

DatagramPacket的构造函数。
void java.net.DatagramSocket.receive(DatagramPacket p)
收。
void java.net.DatagramSocket.send(DatagramPacket p)
发。

2.UDPClient

java.net.DatagramSocket.DatagramSocket() 
客户端的构造函数。
消息的收发同UDPServer。

3.一套示例代码

server:

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

class UDPServer {
	public static void main(String[] args) throws IOException, InterruptedException {
		DatagramSocket server = new DatagramSocket(5050);

		byte[] recvBuf = new byte[100];
		DatagramPacket recvPacket = new DatagramPacket(recvBuf, recvBuf.length);
		while (!Thread.currentThread().isInterrupted()) {
			server.receive(recvPacket);

			String recvStr = new String(recvPacket.getData(), 0, recvPacket.getLength());
			System.out.println("UDPServer receieve:\t" + recvStr);

			int port = recvPacket.getPort();
			InetAddress addr = recvPacket.getAddress();
			String sendStr = "Hello ! I'm Server";
			byte[] sendBuf=sendStr.getBytes();
			DatagramPacket sendPacket = new DatagramPacket(sendBuf, sendBuf.length, addr, port);

			server.send(sendPacket);
			Thread.currentThread().sleep(500);
		}
		server.close();
	}
}
client:

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

class UDPClient {
	public static void main(String[] args) throws IOException, InterruptedException {
		DatagramSocket client = new DatagramSocket();

		String sendStr = "Hello! I'm Client";
		byte[] sendBuf;
		sendBuf = sendStr.getBytes();
		InetAddress addr = InetAddress.getByName("127.0.0.1");
		int port = 5050;
		while (!Thread.currentThread().isInterrupted()) {
			DatagramPacket sendPacket = new DatagramPacket(sendBuf, sendBuf.length, addr, port);
			client.send(sendPacket);
			byte[] recvBuf = new byte[100];
			DatagramPacket recvPacket = new DatagramPacket(recvBuf, recvBuf.length);
			client.receive(recvPacket);
			String recvStr = new String(recvPacket.getData(), 0, recvPacket.getLength());
			System.out.println("UDPClient receieve:\t" + recvStr);
			Thread.currentThread().sleep(500);
		}
		client.close();
	}
}

你可能感兴趣的:(网络)