Java网络编程之UDP

时间:2022-12-17 23:51:04

图一:

Java网络编程之UDP

示例代码:

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

import org.junit.Test;

public class TestUDP {
// 发送端
@Test
public void send() {
DatagramSocket ds = null;
try {
ds = new DatagramSocket();

byte[] b = "我是要发送的信息!".getBytes();
//创建一个数据报:每一个数据报不能大于64k,都记录着数据信息,发送端的IP、端口号,以及要发送到
//的接收端的IP、端口号。
DatagramPacket dp = new DatagramPacket(b, 0, b.length, InetAddress.getByName("127.0.0.1"), 9898);
ds.send(dp);
} catch (SocketException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if(ds != null) {
ds.close();
}
}
}

// 接收端
@Test
public void receive() {
DatagramSocket ds = null;
try {
ds = new DatagramSocket(9898);

byte[] b = new byte[1024];

DatagramPacket dp = new DatagramPacket(b, 0, b.length);
ds.receive(dp);

//String str = new String(b, 0, b.length);
String str = new String(dp.getData(), 0, dp.getLength());
System.out.println(str);
} catch (SocketException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if(ds != null) {
ds.close();
}
}
}
}