最原始:
server
package com.udptest;
import java.io.*;
import java.net.*;
/**
* Created by jiajia on 2017/7/21/021.
*/
public class UDPServer {
public static void main(String[] args) throws IOException {
DatagramSocket server = new DatagramSocket(8080);
byte[] recvBuf = new byte[100];
DatagramPacket recvPacket = new DatagramPacket(recvBuf, recvBuf.length);
server.receive(recvPacket);
String recvStr = new String(recvPacket.getData(), 0, recvPacket .getLength());
System.out.println("客户端传来消息:" + recvStr);
int port = recvPacket.getPort();
InetAddress addr = recvPacket.getAddress();
String sendStr = "Hello ! I'm Server";
byte[] sendBuf;
sendBuf = sendStr.getBytes();
DatagramPacket sendPacket = new DatagramPacket(sendBuf, sendBuf.length,addr, port);
server.send(sendPacket);
server.close();
}
}
client
package com.udptest;
import java.io.*;
import java.net.*;
/**
* Created by jiajia on 2017/7/21/021.
*/
public class UDPClient {
public static void main(String[] args) throws IOException
{
DatagramSocket client = new DatagramSocket();
String sendStr = "Hello! I'm Client";
byte[] sendBuf;
sendBuf = sendStr.getBytes();
InetAddress addr = InetAddress.getByName("10.0.10.220");
int port = 8080;
DatagramPacket sendPacket = new DatagramPacket(sendBuf, sendBuf.length, addr, port);
client.send(sendPacket);
byte[] recvBuf = new byte[100];
DatagramPacket recvPacket = new DatagramPacket(recvBuf, recvBuf.length);
client.receive(recvPacket);
String recvStr = new String(recvPacket.getData(), 0,
recvPacket.getLength());
System.out.println("服务端传来消息:" + recvStr);
client.close();
}
}
使用netty之后的:
public void initServer() {
try {
Bootstrap b = new Bootstrap();
EventLoopGroup group = new NioEventLoopGroup();
b.group(group)
.channel(NioDatagramChannel.class)
.option(ChannelOption.SO_BROADCAST, true)
.handler(new UdpServerHandler());
b.option(ChannelOption.RCVBUF_ALLOCATOR, new FixedRecvByteBufAllocator(65535));
b.bind(searchPort);
} catch (Exception e) {
log.warn("sever 启动失败", e);
}
}
private static class UdpServerHandler extends SimpleChannelInboundHandler<DatagramPacket> {
@Override
protected void channelRead0(ChannelHandlerContext channelHandlerContext, DatagramPacket datagramPacket) throws Exception {
ByteBuf content = datagramPacket.copy().content();
//... ...
//处理数据
}
}