服务端代码
public class UDPChatServer {
//通讯端口
private Integer port=8000;
//数据报文的通讯通道对象
private DatagramChannel channel;
//发送数据的最大大小
private final Integer MAX_SIZE=1024; private Charset charset=Charset.forName("UTF-8"); public UDPChatServer() throws IOException {
//DatagramChannel本身的open方法返回一个DatagramChannel对象
channel=DatagramChannel.open();
//获取数据报的socket对象UDP 的socket
DatagramSocket socket=channel.socket();
//将socket对象绑定上本地的端口
SocketAddress address=new InetSocketAddress(port);
socket.bind(address);
System.out.println("server started!");
}
private void service(){
//初始化一个新的字节缓存对象容量为MAX_SIZE=1024 个字节。
ByteBuffer receiveBuffer=ByteBuffer.allocate(MAX_SIZE);
while (true){
//将缓存中的数据清空
receiveBuffer.clear();
try {
//从渠道中获取固定大小的数据,获取client连接
InetSocketAddress client= (InetSocketAddress) channel.receive(receiveBuffer);
//客户端每次请求到receiveBuffer里
//设置buffer指针的下标0。这样就可以从buffer开头,对该buffer进行遍历(读取)了
receiveBuffer.flip();
//将字节数据转为字符串
String msg= charset.decode(receiveBuffer).toString();
System.out.println(String.format("new data :%s %s %s ",client.getAddress(),client.getPort(),msg));
//应答client 发送数据到通道中的客户端
channel.send(ByteBuffer.wrap(reply(msg).getBytes(charset)),client);
} catch (IOException e) {
e.printStackTrace();
}
}
}
private String reply(String word){
return "you said :"+word;
}
public static void main(String[] args) throws IOException {
new UDPChatServer().service();
}
}
客户端代码:
public class UDPChatClient {
private Integer port=8000;
private String host="localhost";
//UDP socket
private DatagramSocket socket;
private InetAddress address;
private Charset charset=Charset.forName("UTF-8"); public UDPChatClient() throws IOException {
socket=new DatagramSocket();
//设置服务器的地址
address=InetAddress.getByName(host);
System.out.println("connection ok");
}
public static void main(String[] args) throws IOException {
new UDPChatClient().say();
}
private void say() throws IOException {
BufferedReader localreader=new BufferedReader(new InputStreamReader(System.in)); String word;
while ((word=localreader.readLine())!=null){
// 将string转为byte数组 发送udp包
byte[] data=word.getBytes(charset);
//组装包指定ip和端口的数据包
DatagramPacket outputPacket=new DatagramPacket(data,data.length,address,port);
//发送
socket.send(outputPacket);
//接收udp包放到byte数组中
DatagramPacket inputPacket=new DatagramPacket(new byte[1024],1024);
socket.receive(inputPacket);
//打印获取的数据
System.out.println(new String(inputPacket.getData(),0,inputPacket.getLength(),charset)); //客户端主动关闭
if (word.equals("bye")){
socket.close();
break;
} }
}
}