netty 实现socket服务端编写

摘要:
1importjava.net.InetSocketAddress;23importio.netty.bootstrap.ServerBootstrap;4importio.netty.channel.ChannelFuture;5importio.netty.channel.ChannelInitializer;6importio.netty.channel.ChannelOption;7imp
1 importjava.net.InetSocketAddress;
2 
3 importio.netty.bootstrap.ServerBootstrap;
4 importio.netty.channel.ChannelFuture;
5 importio.netty.channel.ChannelInitializer;
6 importio.netty.channel.ChannelOption;
7 importio.netty.channel.EventLoopGroup;
8 importio.netty.channel.nio.NioEventLoopGroup;
9 importio.netty.channel.socket.SocketChannel;
10 importio.netty.channel.socket.nio.NioServerSocketChannel;
11 
12 public classTimeServer {
13     
14     
15     public static void main(String[] args) throwsException{
16         new TimeServer().bind("192.168.1.102", 8400);
17 }
18     
19 
20     public void bind(String addr,intport) {
21         //配置服务端的nio线程组
22         EventLoopGroup boosGroup=newNioEventLoopGroup();
23         EventLoopGroup workerGroup=newNioEventLoopGroup();
24         try{
25             ServerBootstrap b=newServerBootstrap();
26 b.group(boosGroup,workerGroup);
27             b.channel(NioServerSocketChannel.class).option(ChannelOption.SO_BACKLOG,1024)
28             .childHandler(newChildChannelHandler());
29             //绑定端口,同步等待成功
30             ChannelFuture f=b.bind(newInetSocketAddress(addr, port)).sync();
31             //等等服务器端监听端口关闭
32 f.channel().closeFuture().sync();
33         } catch(Exception e) {
34             //TODO: handle exception
35         }finally{
36 boosGroup.shutdownGracefully();
37 workerGroup.shutdownGracefully();
38 }
39 }
40     
41     private class ChildChannelHandler extends ChannelInitializer<SocketChannel>{
42 
43 @Override
44         protected void initChannel(SocketChannel ch) throwsException {
45             ch.pipeline().addLast(newTimeServerHandler());
46             
47 }
48         
49 }
50     
51     
52 }
1 importjava.nio.ByteBuffer;
2 importjava.text.SimpleDateFormat;
3 importjava.util.Date;
4 
5 importio.netty.buffer.ByteBuf;
6 importio.netty.buffer.Unpooled;
7 importio.netty.channel.ChannelHandlerAdapter;
8 importio.netty.channel.ChannelHandlerContext;
9 
10 public class TimeServerHandler extendsChannelHandlerAdapter {
11 
12 @Override
13     public void channelRead(ChannelHandlerContext ctx, Object msg) throwsException {
14         ByteBuf buf=(ByteBuf)msg;
15         byte[] bytes=new byte[buf.readableBytes()];
16 buf.readBytes(bytes);
17         String body=new String(bytes,"UTF-8");
18         SimpleDateFormat  dateFormat=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
19         String time=dateFormat.format(newDate());
20         String res="来自与服务端的回应,时间:"+time;
21         ByteBuf resp=Unpooled.copiedBuffer(res.getBytes());
22 ctx.write(resp);
23         
24 }
25 
26 @Override
27     public void channelReadComplete(ChannelHandlerContext ctx) throwsException {
28 ctx.flush();
29 }
30 
31 @Override
32     public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throwsException {
33 ctx.close();
34 }
35 
36     
37 
38     
39 }

这个比传统的nio好用多了,netty的版本为netty-all-5.0.0.Alpha1.jar

天天学习,天天进步

免责声明:文章转载自《netty 实现socket服务端编写》仅用于学习参考。如对内容有疑问,请及时联系本站处理。

上篇vue用hbuilderX打包app嵌入h5方式云打包和遇到的问题生成中国地区随机IP下篇

宿迁高防,2C2G15M,22元/月;香港BGP,2C5G5M,25元/月 雨云优惠码:MjYwNzM=

相关文章

Twisted框架学习

  Twisted是用Python实现的基于事件驱动的网络引擎框架,是python中一个强大的异步IO库。理解twisted的一个前提是弄清楚twisted中几个核心的概念: reactor, Protocl, ProtocolFactory, Deffered  1 reactor twisted.internet.reactor https://twi...

winform窗体(六)——DataGridView控件及通过此控件中实现增删改查

DataGridView:显示数据表,通过此控件中可以实现连接数据库,实现数据的增删改查 一、后台数据绑定:    List<xxx> list = new List<xxx>();      dataGridView1.DataSource = list;      //设置不自动生成列,此属性在属性面板中没有      data...

python之SQLAlchemy

ORM介绍 orm英文全称object relational mapping,就是对象映射关系程序,简单来说我们类似python这种面向对象的程序来说一切皆对象,但是我们使用的数据库却都是关系型的,为了保证一致的使用习惯,通过orm将编程语言的对象模型和数据库的关系模型建立映射关系,这样我们在使用编程语言对数据库进行操作的时候可以直接使用编程语言的对象模型...

在 foreach 中操作集合时报错:Collection was modified; enumeration operation may not execute.

错误信息:System.InvalidOperationException: Collection was modified; enumeration operation may not execute. 在 foreach 操作集合时就有可能遇到这个错误提示。下面将描述场景并提供解决方案: var dict = new Dictionary<str...

通过HtmlEmail 发送邮件

今天第一次来上海市虹口图书馆上自习,感觉还是很爽的。自己撸代码学会了发送邮件。啥都不说了,直接撸代码吧! 首先 必须引进来三个jar包: compile 'javax.mail:mail:1.4.7'compile 'org.apache.commons:commons-email:1.3.2'compile 'javax.activation:activ...

spark性能调优06-数据倾斜处理

1、数据倾斜 1.1 数据倾斜的现象 现象一:大部分的task都能快速执行完,剩下几个task执行非常慢 现象二:大部分的task都能快速执行完,但总是执行到某个task时就会报OOM,JVM out of Memory,task faild,task lost,resubmitting task等错误 1.2 出现的原因 大部分task分配的数据很少(某...