版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://blog.csdn.net/luo4105/article/details/73650509
DatagramChannel是收发UDP包的通道,与TCP协议不同,UDP发送不进行连接,也不对确认数据是否收到。
DatagramChannel server = DatagramChannel.open();
server.socket().bind(newInetSocketAddress(10086));
此例子是打开10086端口接收udp数据包
通过receive()接收udp包
ByteBuffer receiveBuffer = ByteBuffer.allocate(64);
receiveBuffer.clear();
SocketAddress receiveAddr = server.receive(receiveBuffer);
SocketAddress可以获得发包的ip、端口等信息,用toString查看,格式如下
/127.0.0.1:57126
通过send()发送udp包
DatagramChannel server = DatagramChannel.open();
ByteBuffer sendBuffer = ByteBuffer.wrap("client send".getBytes());
server.send(sendBuffer, new InetSocketAddress("127.0.0.1",10086));
udp不存在真正意义上的连接,这里的连接是向特定服务地址用read和write接收发送数据包。
client.connect(new InetSocketAddress("127.0.0.1",10086));
int readSize= client.read(sendBuffer);
server.write(sendBuffer);
read()和write()只有在connect()后才能使用,不然会抛NotYetConnectedException异常。用read()接收时,如果没有接收到包,会抛PortUnreachableException异常。
客户端发送,服务端接收的例子
/**
* 发包的datagram
*
* @throws IOException
* @throws InterruptedException
*/
@Test
public voidsendDatagram() throwsIOException, InterruptedException {
DatagramChannelsendChannel= DatagramChannel.open();
InetSocketAddresssendAddress= newInetSocketAddress("127.0.0.1", 9999);
while (true) {
sendChannel.send(ByteBuffer.wrap("发包".getBytes("UTF-8")), sendAddress);
System.out.println("发包端发包");
Thread.sleep(1000);
}
}
/**
* 收包端
*
* @throws IOException
*/
@Test
public voidreceive() throwsIOException {
DatagramChannelreceiveChannel= DatagramChannel.open();
InetSocketAddressreceiveAddress= newInetSocketAddress(9999);
receiveChannel.bind(receiveAddress);
ByteBufferreceiveBuffer= ByteBuffer.allocate(512);
while (true) {
receiveBuffer.clear();
SocketAddresssendAddress= receiveChannel.receive(receiveBuffer);
receiveBuffer.flip();
System.out.print(sendAddress.toString() + " ");
System.out.println(Charset.forName("UTF-8").decode(receiveBuffer));
}
}
/**
* 只接收和发送9999的数据包
*
* @throws IOException
*/
@Test
public voidtestConect1() throwsIOException {
DatagramChannelconnChannel= DatagramChannel.open();
connChannel.bind(newInetSocketAddress(9998));
connChannel.connect(new InetSocketAddress("127.0.0.1",9999));
connChannel.write(ByteBuffer.wrap("发包".getBytes("UTF-8")));
ByteBufferreadBuffer= ByteBuffer.allocate(512);
while (true) {
try {
readBuffer.clear();
connChannel.read(readBuffer);
readBuffer.flip();
System.out.println(Charset.forName("UTF-8").decode(readBuffer));
}catch(Exception e) {
}
}
}
/**
* 只接收和发送9998的数据包
*
* @throws IOException
*/
@Test
public voidtestConect2() throwsIOException {
DatagramChannelconnChannel= DatagramChannel.open();
connChannel.bind(newInetSocketAddress(9999));
connChannel.connect(new InetSocketAddress("127.0.0.1",9998));
while (true) {
connChannel.write(ByteBuffer.wrap("发包".getBytes("UTF-8")));
System.out.println("发包成功");
}
}