您的位置:首页 > 其它

netty框架的udp方式的简单实现

2015-11-27 14:18 369 查看
    最近在开发的项目中使用到了局域网的扫描发现功能,后来通过学习通过netty框架实现了这个功能,虽然很简单但是刚开始却不知道怎么做,记录一下。

服务端的代码:

**
* 搜索的实现,基于netty的udp
*/
public class SearchServer {
public static void initServer() {//udp服务端,接受客户端发送的广播
try {
Bootstrap b = new Bootstrap();
EventLoopGroup group = new NioEventLoopGroup();
b.group(group)
.channel(NioDatagramChannel.class)
.option(ChannelOption.SO_BROADCAST, true)
.handler(new UdpServerHandler());
b.bind(AppConstants.SEARCH_PORT).sync().channel().closeFuture().await();
} catch (InterruptedException e) {
e.printStackTrace();
}
}

private static class UdpServerHandler extends SimpleChannelInboundHandler<DatagramPacket> {
@Override
protected void messageReceived(ChannelHandlerContext ctx, DatagramPacket packet) throws Exception {
ByteBuf buf = packet.copy().content();
byte[] req = new byte[buf.readableBytes()];
buf.readBytes(req);
String body = new String(req, "UTF-8");
Log.d("TAG", body);
System.out.println(body);//打印收到的信息

//向客户端发送消息
String json = "给客户端发送的内容";

// 由于数据报的数据是以字符数组传的形式存储的,所以传转数据
byte[] bytes = json.getBytes("UTF-8");
DatagramPacket data = new DatagramPacket(Unpooled.copiedBuffer(bytes), packet.sender());
ctx.writeAndFlush(data);//向客户端发送消息
}
}

}


客户端代码如下:

public class SearchClient {

public static final int MessageReceived = 0x99;
private int scanPort;

public SearchClient(int scanPort) {
this.scanPort = scanPort;
}

private static class CLientHandler extends SimpleChannelInboundHandler<DatagramPacket> {
@Override
protected void messageReceived(ChannelHandlerContext ctx,
DatagramPacket packet) throws Exception {

String  body =  packet.content().toString(CharsetUtil.UTF_8);
Log.i("Search", "body:" + body);
//这里接收到服务端发送的内容

}
}

public void sendPackage() {
EventLoopGroup group = new NioEventLoopGroup();
try {
Bootstrap b = new Bootstrap();
b.group(group)
.channel(NioDatagramChannel.class)
.option(ChannelOption.SO_BROADCAST, true)
.handler(new CLientHandler());

Channel ch = b.bind(0).sync().channel();

ch.writeAndFlush(new DatagramPacket(
Unpooled.copiedBuffer("Searh:", CharsetUtil.UTF_8),
new InetSocketAddress("255.255.255.255", scanPort))).sync();

Log.i("Searh","sendPackage()");

// QuoteOfTheMomentClientHandler will close the DatagramChannel when a
// response is received.  If the channel is not closed within 5 seconds,
// print an error message and quit.
if (!ch.closeFuture().await(5000)) {
System.err.println("Search request timed out.");
}
}catch (Exception e){
e.printStackTrace();
Log.e("Search","An Error Occur",e);
}
finally {
group.shutdownGracefully();
}
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息