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(); } } }
相关文章推荐
- Window快捷键简介
- Activity生命周期---横竖屏切换的生命周期
- 滴滴快车奖励政策,高峰奖励,翻倍奖励,按成交率,指派单数分级(11月21日~11月27日)
- iOS开发日记50-文本转语音(TTS)
- python 跳板机登录脚本
- Protractor - 怎样运行
- Windows Server 2008修改IE浏览器级别便于使用
- MFC笔记6
- 大数据批量插入数据库
- 判断String为空
- 1、jxl导入/导出excel案例,黏贴即可运行
- php读取目录及子目录下所有文件名
- Android M(6.0) 中删除Apache HTTP Client的解决方案
- c3p0数据库连接池问题-----不能取到连接An attempt by a client to checkout a Connection has timed out(问题还没有解决)
- c#实现c语言memcpy各种类型转换
- 使用JQuery上传图片 实现预览
- Linux安装配置maven以及搭建nexus私服
- ADO连接达梦7数据库,利用OLEDB建立连接
- mysqlbinlog日志一天产生太多脚本
- 通讯录获取和带号码分区排序