在java中使用UDP传输数据比TCP更加简单。和socket的TCP不同,UDP不是面向连接的协议。使用UDP时,只要知道服务器IP和端口就可以直接向对方发送数据。在java中使用DatagramChannel来处理UDP的数据传输。 在服务端,首先调用bind()方法绑定DatagramChannel的监听端口。当数据来到时调用了revice()方法,DatagramChannel接收数据后曦儿ByteBuffer缓冲区。
public class UDPClient {
public static void main(String[] args) {
new UDPClient().send();
}
@SneakyThrows
public void send() {
DatagramChannel channel = DatagramChannel.open();
channel.configureBlocking(false);
ByteBuffer buffer = ByteBuffer.allocate(1024);
Scanner scanner = new Scanner(System.in);
log.info("UDP客户端启动成功!");
log.info("请输入发送内容:");
while (scanner.hasNext()) {
String next = scanner.next();
Date date = new Date();
buffer.put((date + ">>"+next).getBytes());
buffer.flip();
channel.send(buffer, new InetSocketAddress("127.0.0.1", 8888));
buffer.clear();
}
channel.close();
}
}
@SneakyThrows
public void receive(){
DatagramChannel channel = DatagramChannel.open();
channel.configureBlocking(false);
channel.bind(new InetSocketAddress("127.0.0.1",8888));
Selector selector = Selector.open();
channel.register(selector,SelectionKey.OP_READ);
while (selector.select()>0){
Iterator<SelectionKey> iterator = selector.selectedKeys().iterator();
ByteBuffer buffer = ByteBuffer.allocate(1024);
while (iterator.hasNext()){
SelectionKey selectionKey = iterator.next();
if(selectionKey.isReadable()){
SocketAddress address = channel.receive(buffer);
buffer.flip();
log.info(new String(buffer.array(),0,buffer.limit()));
buffer.clear();
}
}
iterator.remove();
}
selector.close();
channel.close();
}
|