DatagramChannel用法
1.打开DatagramChannel
DatagramChannel server = DatagramChannel.open();
server.socket().bind(new InetSocketAddress(10086));
此例子是打开10086端口接收UDP接收包
2.接收数据
通过receive()接收UDP包
ByteBuffer receiveBuffer = ByteBuffer.allocate(64);
receiveBuffer.clear();
SocketAddress receiveAddr = server.receive(receiveBuffer);
SocketAddress可以获得发包的ip,端口等信息,用toString查看,格式如下/127.0.0.1:57126
3.发送数据
通过send()发送UDP包
DatagramChannel server = DatagramChannel.open();
ByteBuffer sendBuffer = ByteBuffer.wrap("client send".getBytes());
server.send(sendBuffer,new InetSocketAddress("127.0.0.1",10086));
4.连接
UDP不存在真正意义上的连接,这里的连接是向特定服务地址用write和read接收发送数据包
server.connect(new InetSocketAddress("127.0.0.1",10086));
int redSize = server.read(receiveBuffer);
server.write(sendBuffer);
read()和write()只有在connect()后才能使用,不然会抛NotYetConnectedException异常.用read()接收时,如果没有接收包,会抛PortUnreachableException
5.DatagramChannel示例
客户端发送,服务端接收的例子
package FileChannel演示;
import org.junit.Test;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.SocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.DatagramChannel;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
public class DatagramChannelDemo {
@Test
public void sendDatagram() throws IOException, InterruptedException {
DatagramChannel sendChannel = DatagramChannel.open();
InetSocketAddress sendAddress = new InetSocketAddress("127.0.0.1",9999);
while(true) {
ByteBuffer buffer = ByteBuffer.wrap("你好,我是顾文韬".getBytes(StandardCharsets.UTF_8));
sendChannel.send(buffer,sendAddress);
System.out.println("已经发送完成");
Thread.sleep(1000);
}
}
@Test
public void receiveDatagram() throws IOException {
DatagramChannel receiveChannel = DatagramChannel.open();
InetSocketAddress sendAddress = new InetSocketAddress(9999);
receiveChannel.bind(sendAddress);
ByteBuffer buffer = ByteBuffer.allocate(1024);
while(true) {
buffer.clear();
SocketAddress socketAddress = receiveChannel.receive(buffer);
buffer.flip();
System.out.println(socketAddress.toString());
System.out.println(Charset.forName("UTF-8").decode(buffer));
}
}
}
@Test
public void testConnect() throws IOException {
DatagramChannel connChannel = DatagramChannel.open();
connChannel.bind(new InetSocketAddress(9999));
connChannel.connect(new InetSocketAddress("127.0.0.1",9999));
connChannel.write(ByteBuffer.wrap("你好,我是顾文韬".getBytes(StandardCharsets.UTF_8)));
ByteBuffer buffer = ByteBuffer.allocate(1024);
while(true) {
buffer.clear();
connChannel.read(buffer);
buffer.flip();
System.out.println(Charset.forName("UTF-8").decode(buffer));
}
}
|