Java网络编程—UDP协议测试

如何使用:先启动UDPAccept开启接收,再启动UDPSend发送数据。

package com.java;

import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.SocketException;
//接收端
public class UDPAccept {
	public static void main(String[] args) throws Exception {
		DatagramSocket ds = new DatagramSocket(11000);
		byte[] b = new byte[1024];
		DatagramPacket dp = new DatagramPacket(b, b.length);
		ds.receive(dp);//接收不到数据包,阻塞
		System.out.println(dp.getLength());
		System.out.println(new String(b, 0, dp.getLength(), "UTF-8"));
	}
}

package com.java;

import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;
//发送端
public class UDPSend {
	public static void main(String[] args) throws Exception {
		// 发送一个数据包
		//创建socket对象用于发送接收套接字
		DatagramSocket ds = new DatagramSocket();
		String s = "UDP测试。";
		//封装数据包
		DatagramPacket dp = new DatagramPacket(s.getBytes("UTF-8"), s.getBytes("UTF-8").length, InetAddress.getLocalHost(), 11000);
		ds.send(dp);
		ds.close();
	}
}

你可能感兴趣的:(朝花夕誓—Java)