前面一文说了 基于http的netty demo

和http不一样,http可以用浏览器来充当客户端调用,所以基于socket的netty,必须要编写客户端和服务器的代码

实现功能:

客户端给服务器发消息,服务器给客户端回消息

一直循环

服务器代码

 1 package com.bill.socketdemo;
2
3
4 import io.netty.bootstrap.ServerBootstrap;
5 import io.netty.channel.ChannelFuture;
6 import io.netty.channel.EventLoopGroup;
7 import io.netty.channel.nio.NioEventLoopGroup;
8 import io.netty.channel.socket.nio.NioServerSocketChannel;
9
10 public class SocketServer {
11
12 public static void main(String[] args) throws Exception {
13
14 // 这2个group都是死循环,阻塞式
15 EventLoopGroup bossGroup = new NioEventLoopGroup();
16 EventLoopGroup workerGroup = new NioEventLoopGroup();
17
18 try {
19 ServerBootstrap serverBootstrap = new ServerBootstrap();
20 serverBootstrap.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class).
21 childHandler(new SocketServerInitializer());
22
23 ChannelFuture channelFuture = serverBootstrap.bind(8899).sync();
24 channelFuture.channel().closeFuture().sync();
25 } finally {
26 bossGroup.shutdownGracefully();
27 workerGroup.shutdownGracefully();
28 }
29 }
30
31 }
32
33 package com.bill.socketdemo;
34
35 import io.netty.channel.ChannelHandlerContext;
36 import io.netty.channel.SimpleChannelInboundHandler;
37
38 import java.util.UUID;
39
40 public class SocketServerHandler extends SimpleChannelInboundHandler<String> {
41
42 /**
43 * 读取客户端请求,并且返回给客户端数据的方法
44 */
45 @Override
46 protected void channelRead0(ChannelHandlerContext ctx, String msg) throws Exception {
47 System.out.println(ctx.channel().remoteAddress() + ", " + msg);
48 ctx.channel().writeAndFlush("from server:" + UUID.randomUUID());
49 }
50
51 /**
52 * 处理异常的方法,一旦出现异常,就会调用此方法
53 */
54 @Override
55 public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
56 cause.printStackTrace();
57 ctx.close();
58 }
59 }
60
61 package com.bill.socketdemo;
62
63 import io.netty.channel.ChannelInitializer;
64 import io.netty.channel.ChannelPipeline;
65 import io.netty.channel.socket.SocketChannel;
66 import io.netty.handler.codec.LengthFieldBasedFrameDecoder;
67 import io.netty.handler.codec.LengthFieldPrepender;
68 import io.netty.handler.codec.string.StringDecoder;
69 import io.netty.handler.codec.string.StringEncoder;
70 import io.netty.util.CharsetUtil;
71
72 public class SocketServerInitializer extends ChannelInitializer<SocketChannel> {
73
74 @Override
75 protected void initChannel(SocketChannel socketChannel) throws Exception {
76
77 ChannelPipeline pipeline = socketChannel.pipeline();
78
79 pipeline.addLast("LengthFieldBasedFrameDecoder", new LengthFieldBasedFrameDecoder(Integer.MAX_VALUE, 0, 4, 0, 4));
80 pipeline.addLast("LengthFieldPrepender",new LengthFieldPrepender(4));
81 pipeline.addLast("StringDecoder",new StringDecoder(CharsetUtil.UTF_8));
82 pipeline.addLast("StringEncoder",new StringEncoder(CharsetUtil.UTF_8));
83 pipeline.addLast("SocketServerHandler", new SocketServerHandler());
84 }
85 }

客户端代码

 1 package com.bill.socketdemo;
2
3
4 import io.netty.bootstrap.Bootstrap;
5 import io.netty.channel.ChannelFuture;
6 import io.netty.channel.EventLoopGroup;
7 import io.netty.channel.nio.NioEventLoopGroup;
8 import io.netty.channel.socket.nio.NioSocketChannel;
9
10 public class SocketClient {
11
12 public static void main(String[] args) throws Exception {
13
14 // 这2个group都是死循环,阻塞式
15 EventLoopGroup eventLoopGroup = new NioEventLoopGroup();
16
17 try {
18 Bootstrap bootstrap = new Bootstrap();
19 bootstrap.group(eventLoopGroup).channel(NioSocketChannel.class).
20 handler(new SocketClientInitializer());
21
22 ChannelFuture channelFuture = bootstrap.connect("localhost", 8899).sync();
23 channelFuture.channel().closeFuture().sync();
24 } finally {
25 eventLoopGroup.shutdownGracefully();
26 }
27 }
28
29 }
30
31 package com.bill.socketdemo;
32
33 import io.netty.channel.ChannelHandlerContext;
34 import io.netty.channel.SimpleChannelInboundHandler;
35
36 import java.util.UUID;
37
38 public class SocketClientHandler extends SimpleChannelInboundHandler<String> {
39
40 /**
41 * 发送内容给服务器端
42 */
43 @Override
44 protected void channelRead0(ChannelHandlerContext ctx, String msg) throws Exception {
45 System.out.println(ctx.channel().remoteAddress());
46 System.out.println("client output:" + msg);
47 ctx.writeAndFlush("from client:" + UUID.randomUUID());
48 }
49
50 /**
51 * 该方法向服务器发数据,打破服务器-客户端一直等待对方发数据的僵局
52 */
53 @Override
54 public void channelActive(ChannelHandlerContext ctx) throws Exception {
55 ctx.writeAndFlush("from client: hello world");
56 }
57
58 /**
59 * 处理异常的方法,一旦出现异常,就会调用此方法
60 */
61 @Override
62 public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
63 cause.printStackTrace();
64 ctx.close();
65 }
66 }
67
68 package com.bill.socketdemo;
69
70 import io.netty.channel.ChannelInitializer;
71 import io.netty.channel.ChannelPipeline;
72 import io.netty.channel.socket.SocketChannel;
73 import io.netty.handler.codec.LengthFieldBasedFrameDecoder;
74 import io.netty.handler.codec.LengthFieldPrepender;
75 import io.netty.handler.codec.string.StringDecoder;
76 import io.netty.handler.codec.string.StringEncoder;
77 import io.netty.util.CharsetUtil;
78
79 public class SocketClientInitializer extends ChannelInitializer<SocketChannel> {
80
81 @Override
82 protected void initChannel(SocketChannel socketChannel) throws Exception {
83
84 ChannelPipeline pipeline = socketChannel.pipeline();
85
86 pipeline.addLast("LengthFieldBasedFrameDecoder", new LengthFieldBasedFrameDecoder(Integer.MAX_VALUE, 0, 4, 0, 4));
87 pipeline.addLast("LengthFieldPrepender",new LengthFieldPrepender(4));
88 pipeline.addLast("StringDecoder",new StringDecoder(CharsetUtil.UTF_8));
89 pipeline.addLast("StringEncoder",new StringEncoder(CharsetUtil.UTF_8));
90 pipeline.addLast("SocketServerHandler", new SocketClientHandler());
91 }
92 }

执行结果

先运行服务器:

再运行客户端:

运行完客户端后服务器的情况

完整代码下载:

https://download.csdn.net/download/mweibiao/10551574

基于socket的netty demo的更多相关文章

  1. 基于websocket的netty demo

    前面2文 基于http的netty demo 基于socket的netty demo 讲了netty在http和socket的使用,下面讲讲netty如何使用websocket websocket是h ...

  2. 基于http的netty demo

    1.引入netty的pom <dependency> <groupId>io.netty</groupId> <artifactId>netty-all ...

  3. Android 基于Socket的聊天应用(二)

    很久没写BLOG了,之前在写Android聊天室的时候答应过要写一个客户(好友)之间的聊天demo,Android 基于Socket的聊天室已经实现了通过Socket广播形式的通信功能. 以下是我写的 ...

  4. 与众不同 windows phone (31) - Communication(通信)之基于 Socket UDP 开发一个多人聊天室

    原文:与众不同 windows phone (31) - Communication(通信)之基于 Socket UDP 开发一个多人聊天室 [索引页][源码下载] 与众不同 windows phon ...

  5. 与众不同 windows phone (30) - Communication(通信)之基于 Socket TCP 开发一个多人聊天室

    原文:与众不同 windows phone (30) - Communication(通信)之基于 Socket TCP 开发一个多人聊天室 [索引页][源码下载] 与众不同 windows phon ...

  6. c#编写的基于Socket的异步通信系统

    c#编写的基于Socket的异步通信系统 SanNiuSignal是一个基于异步socket的完全免费DLL:它里面封装了Client,Server以及UDP:有了这个DLL:用户不用去关心心跳:粘包 ...

  7. 基于socket.io的实时在线选座系统

    基于socket.io的实时在线选座系统(demo) 前言 前段时间公司做一个关于剧院的项目,遇到了这样一种情况. 在高并发多用户同时选座的情况下,假设A用户进入选座页面,正在选择座位,此时还没有提交 ...

  8. 基于websocket vue 聊天demo 解决方案

    基于websocket vue 聊天demo 解决方案 demo 背景 电商后台管理的客服 相关技术 vuex axios vue websocket 聊天几种模型 一对一模型 一对一 消息只一个客户 ...

  9. 基于Socket客户端局域网或广域网内共享同一短信猫收发短信的开发解决方案

    可使同一网络(局域网或广域网)内众多客户端,共享一个短信猫设备短信服务器进行短信收发,短信服务器具备对客户端的管理功能. 下面是某市建设银行采用本短信二次开发平台时实施的系统方案图: 在该方案中,考虑 ...

随机推荐

  1. PP-OCR论文翻译

    译者注: 我有逛豆瓣社区的习惯,因此不经意间会看到一些外文翻译成中文书的评价."书是好书,翻译太臭"."中文版别看"."有能力尽量看原版". ...

  2. PyQt(Python+Qt)学习随笔:Model/View中的枚举类 Qt.MatchFlag的取值及含义

    老猿Python博文目录 专栏:使用PyQt开发图形界面Python应用 老猿Python博客地址 枚举类 Qt.MatchFlag描述在模型中搜索项时可以使用的匹配类型,它可以在QStandardI ...

  3. PyQt(Python+Qt)学习随笔:model/view架构中的QStandardItemModel使用案例

    老猿Python博文目录 专栏:使用PyQt开发图形界面Python应用 老猿Python博客地址 1.案例说明 在应用中展示指定目录的图标文件的文件名和图标,界面就是一个简单的窗口上面放置一名为li ...

  4. PyQt(Python+Qt)学习随笔:QAbstractItemView的iconSize属性

    老猿Python博文目录 老猿Python博客地址 视图的iconSize属性用于控制显示icon的项上的icon图标大小,在视图可见情况下设置该属性会导致视图上的显示项重新调整布局. 可以使用ico ...

  5. pandas 由其中几列生成新的列

    data是一个dataframe #data["x1"]=data[["a","b"]].apply(lambda x:x["a& ...

  6. bootstrap table 嵌入百分比进度条

  7. 在Linux中使用Dbeaver等GTK3界面的软件出现频繁闪烁的问题解决

    问题复现 复现环境LinuxMint 19 Dbeaver: 7.3 输入法: ibus + ibus-table-wubi 如图,当光标移动到Sql Editor中会不停的闪-- 解决过程 先百度. ...

  8. 树的直径,LCA复习笔记

    前言 复习笔记第6篇. 求直径的两种方法 树形DP: dfs(y); ans=max( ans,d[x]+d[y]+w[i] ); d[x]=max( d[x],d[y]+w[i] ); int di ...

  9. POJ3565

    题目大意: 给定\(n\)个蚂蚁和\(n\)颗苹果树的坐标,要求每个蚂蚁爬到一颗苹果树旁,使得每个蚂蚁路线不相交且路线总长度最小,求每个蚂蚁爬到哪个苹果树旁? 首先假设有两只蚂蚁路径相交,那么这两个蚂 ...

  10. Acwing 393. 雇佣收银员

    算法1: 差分约束 + 枚举 O(Tn2028) 由于牵扯到 \([i - 8 + 1, i]\) 这段区间的和的约束,所以用前缀和更好表达一些. 设 \(num[i]\)表示 \(i\) 时刻有多少 ...