基于socket的netty demo
前面一文说了 基于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的更多相关文章
- 基于websocket的netty demo
前面2文 基于http的netty demo 基于socket的netty demo 讲了netty在http和socket的使用,下面讲讲netty如何使用websocket websocket是h ...
- 基于http的netty demo
1.引入netty的pom <dependency> <groupId>io.netty</groupId> <artifactId>netty-all ...
- Android 基于Socket的聊天应用(二)
很久没写BLOG了,之前在写Android聊天室的时候答应过要写一个客户(好友)之间的聊天demo,Android 基于Socket的聊天室已经实现了通过Socket广播形式的通信功能. 以下是我写的 ...
- 与众不同 windows phone (31) - Communication(通信)之基于 Socket UDP 开发一个多人聊天室
原文:与众不同 windows phone (31) - Communication(通信)之基于 Socket UDP 开发一个多人聊天室 [索引页][源码下载] 与众不同 windows phon ...
- 与众不同 windows phone (30) - Communication(通信)之基于 Socket TCP 开发一个多人聊天室
原文:与众不同 windows phone (30) - Communication(通信)之基于 Socket TCP 开发一个多人聊天室 [索引页][源码下载] 与众不同 windows phon ...
- c#编写的基于Socket的异步通信系统
c#编写的基于Socket的异步通信系统 SanNiuSignal是一个基于异步socket的完全免费DLL:它里面封装了Client,Server以及UDP:有了这个DLL:用户不用去关心心跳:粘包 ...
- 基于socket.io的实时在线选座系统
基于socket.io的实时在线选座系统(demo) 前言 前段时间公司做一个关于剧院的项目,遇到了这样一种情况. 在高并发多用户同时选座的情况下,假设A用户进入选座页面,正在选择座位,此时还没有提交 ...
- 基于websocket vue 聊天demo 解决方案
基于websocket vue 聊天demo 解决方案 demo 背景 电商后台管理的客服 相关技术 vuex axios vue websocket 聊天几种模型 一对一模型 一对一 消息只一个客户 ...
- 基于Socket客户端局域网或广域网内共享同一短信猫收发短信的开发解决方案
可使同一网络(局域网或广域网)内众多客户端,共享一个短信猫设备短信服务器进行短信收发,短信服务器具备对客户端的管理功能. 下面是某市建设银行采用本短信二次开发平台时实施的系统方案图: 在该方案中,考虑 ...
随机推荐
- 极简python教程02:基础变量,删繁就简
python极简教程已经开赛,如果错过说明可以回翻: 极简python教程:赛前说明 借这个机会,我再讲讲我的教程和其他网上的教程的区别: 1 我分享的内容,是我在工作中会高频使用的语法,是精华内容 ...
- moviepy执行TextClip.search方法时报错TypeError: a bytes-like object is required, not str
☞ ░ 前往老猿Python博文目录 ░ 执行TextClip.search方法时,报错: >>> from moviepy.editor import * >>> ...
- PyQt(Python+Qt)学习随笔:QListWidget查找项的findItems方法
老猿Python博文目录 专栏:使用PyQt开发图形界面Python应用 老猿Python博客地址 QListWidget列表部件的findItems方法用于查找列表部件是否有满足条件的项,调用语法如 ...
- PyQt(Python+Qt)学习随笔:PyQt界面派生类构造方法中super方法的使用
老猿Python博文目录 专栏:使用PyQt开发图形界面Python应用 老猿Python博客地址 在<第15.7节 PyQt入门学习:PyQt5应用构建详细过程介绍>和订阅专栏<第 ...
- PyQt(Python+Qt)学习随笔:model/view架构中支持QListView列表中展示图标的两种方法
老猿Python博文目录 专栏:使用PyQt开发图形界面Python应用 老猿Python博客地址 在QListView列表视图中的项不但可以展示文字,也可以展示图标和复选框,同时可以指定项是否可以拖 ...
- B站自动爬取器并制作词云
效果 词云展示 弹幕展示 爬取弹幕过程 基本步骤 1.寻找视频url 2.构造请求头 3.寻找弹幕地址 4.根据弹幕地址运用正则或xpath爬取 寻找B站视频的url 制作请求头 headers = ...
- MySQL Docker容器实例创建并进入MySQL命令行
首先需要明白的一点是: docker镜像是一个模版,docker容器是一个实例,它可以被启动与关闭. 我们需要先有MySQL的docker镜像,使用命令: docker pull mysql 拉取最新 ...
- secret_key伪造session来进行越权
从swpuctf里面的一道ctf题目来讲解secret_key伪造session来进行越权. 以前没有遇到过这种题目,这次遇到了之后查了一些资料把它做了出来,记录一下知识点. 参考资料 http:// ...
- 微信小程序template和组件
template主要是展示,主要是在调用的页面中定义.用import方式引入,然后去使用,通常是单独建立一个文件夹 去管理,文件夹有两个文件wxml和wxss,wxml中 可以定义多个template ...
- redis学习之——CentOS 6 下载安装redis
一.检查当前环境: 安装过程中没有这些,命令,在CentOS 6,最小安装导致..如果执行完命令,Noting to do...字样说明环境正常. yum -y install rpm gcc w ...