package com.iphanta.service;
import java.net.InetSocketAddress;
import java.net.SocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.DatagramChannel;
import java.nio.charset.StandardCharsets;
/**
* upd 通道
* @Author: Jim
* @Date: 2021/10/15 17:36
*/
public class DatagramSocketChannelDemo {
public static void main(String[] args) throws Exception {
startServer(10086);
}
//启动udp 服务端
public static void startServer(int port) throws Exception{
DatagramChannel open = DatagramChannel.open();
open.socket().bind(new InetSocketAddress(port));
System.err.println("udp server start port:" + port);
ByteBuffer buffer = ByteBuffer.allocate(1024);
//收消息
while (true) {
buffer.clear();
System.err.println("接受消息中..");
SocketAddress socketAddress = open.receive(buffer);
buffer.flip();
System.err.println(socketAddress);
System.out.println(StandardCharsets.UTF_8.decode(buffer));
}
}
//udp 发消息
public static void send() throws Exception{
DatagramChannel open = DatagramChannel.open();
//发消息
open.send(ByteBuffer.wrap("hello".getBytes()), new InetSocketAddress("127.0.0.1", 10086));
System.err.println("发送完成");
}
}
|