NIO 学习笔记三:DatagramChannel

Java NIO中的DatagramChannel是一个能收发UDP包的通道。因为UDP是无连接的网络协议,所以不能像其它通道那样读取和写入。它发送和接收的是数据包。

打开 DatagramChannel,绑定9999端口

DatagramChannel channel = DatagramChannel.open();
channel.socket().bind(new InetSocketAddress(9999));

接收数据

通过receive()方法从DatagramChannel接收数据,如:

ByteBuffer buf = ByteBuffer.allocate(48);
buf.clear();
channel.receive(buf);
receive()方法会将接收到的数据包内容复制到指定的Buffer. 如果Buffer容不下收到的数据,多出的数据将被丢弃。

发送数据

通过send()方法从DatagramChannel发送数据,如:

String newData = "New String to write to file..." + System.currentTimeMillis();

ByteBuffer buf = ByteBuffer.allocate(48);
buf.clear();
buf.put(newData.getBytes());
buf.flip();

int bytesSent = channel.send(buf, new InetSocketAddress("jenkov.com", 80));
这个例子发送一串字符到”jenkov.com”服务器的UDP端口80。

示例
服务端代码:
public static void main(String[] args) throws Exception {
DatagramChannel channel = DatagramChannel.open();
channel.socket().bind(new InetSocketAddress("10.10.167.150", 90));
ByteBuffer buffer = ByteBuffer.allocate(1000);
buffer.clear();
SocketAddress socketAddress = channel.receive(buffer);
byte b[];
if (socketAddress != null) {
int position = buffer.position();
b = new byte[position];
buffer.flip();
for (int i = 0; i < position; ++i) {
b[i] = buffer.get();
}
System.out.println("receive remote " + socketAddress.toString() + ":" + new String(b, "UTF-8"));
//接收到消息后给发送方回应
sendReback(channel, socketAddress);
}
}

public static void sendReback(DatagramChannel channel, SocketAddress socketAddress) throws Exception {
String str = "接收到你的信息";
ByteBuffer buffer = ByteBuffer.allocate(1000);
buffer.put(str.getBytes("UTF-8"));
buffer.flip();
channel.send(buffer, socketAddress);
}
客户端代码:
public static void main(String[] args) throws Exception {
final DatagramChannel channel = DatagramChannel.open();
new Thread(new Runnable() {
@Override
public void run() {
ByteBuffer buffer = ByteBuffer.allocate(1000);
buffer.clear();
SocketAddress socketAddress = null;
try {
socketAddress = channel.receive(buffer);
} catch (Exception e) {
e.printStackTrace();
}
byte b[];
if (socketAddress != null) {
int position = buffer.position();
b = new byte[position];
buffer.flip();
for (int i = 0; i < position; ++i) {
b[i] = buffer.get();
}
try {
System.out.println("receive remote " + socketAddress.toString() + ":" + new String(b, "UTF-8"));
} catch (Exception e) {
e.printStackTrace();
}
}

}
}).start();
while (true) {
Scanner scanner = new Scanner(System.in);
String next = scanner.next();
sendMessage(channel, next);
}
}

public static void sendMessage(DatagramChannel channel, String message) throws Exception {
if (message == null && message.isEmpty()) {
return;
}
ByteBuffer buffer = ByteBuffer.allocate(1000);
buffer.clear();
buffer.put(message.getBytes("UTF-8"));
buffer.flip();
channel.send(buffer, new InetSocketAddress("10.10.167.150", 90));
}

posted @ 2018-05-12 09:23  霸王猿  阅读(212)  评论(0编辑  收藏  举报