前面一文说了 基于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. Python使用import导入模块时执行了模块的文件但报ModuleNotFoundError错误的愚蠢问题

    老猿在学习import导入自定义模块时,搜索路径中sys.path中已经添加对应路径,发现会报ModuleNotFoundError,但对应的模块代码被执行了,代码myfib.py如下: def fi ...

  2. 第10.4节 Python模块的弱封装机制

    一. 引言 Python模块可以为调用者提供模块内成员的访问和调用,但某些情况下, 因为某些成员可能有特殊访问规则等原因,并不适合将模块内所有成员都提供给调用者访问,此时模块可以类似类的封装机制类似的 ...

  3. PyQt(Python+Qt)学习随笔:Qt Designer中部件的焦点策略focusPolicy设置

    在Qt Designer中可以设置部件的焦点策略,部件的焦点策略属性取值范围由枚举类型Qt.FocusPolicy来定义,该枚举类型及其含义如下表所示: 注意:经老猿测试鼠标轮滚动获取焦点,只有在鼠标 ...

  4. 【ZJOI2019】线段树(线段树 & dp)

    Link UOJ LOJ Luogu Solution 很玄妙的一道题,考察了对线段树较本质的理解 然而我并不会这个所谓最可做的题 首先,虽然题目很复杂,好像每个点的标记变化都很玄学,但是我们可以深入 ...

  5. python(iJmeter-master)接口测试程序部署实践

    记录学习性能测试过程遇到的问题 环境 安装环境如下: Windows 10 1803 VMWare Workstation 15 Pro Centos Linux release 7.9.2009(c ...

  6. 三方登录微博url接口

    1.创建apps/oauth模块进行oauth认证 '''2.1 在apps文件夹下新建应用: oauth''' cd syl/apps python ../manage.py startapp oa ...

  7. vue检查用户名是否重复

    前端函数如下,js方法代码无需更改,前端代码逻辑在components\common\lab_header.vue 只需要修改components\axios_api\http.js中调用的后端地址 ...

  8. 查询是否sci或者ei收录

    1,如果查文章是不是被SCI检索:进入ISI Web of Knowledge,选择Web of Science 数据库,进行查询:2,如果查文章是不是被EI检索:进入EI Village, 选择Co ...

  9. Mac电脑完美解决 BasicIPv6ValidationError 问题,通过命令行更改ip设置

    在更改mac电脑ip网络时,提示BasicIPv6ValidationError.

  10. 移动端 CSS3动画属性

    一.transform 转换属性 #1. translate位移 transform : translate(50px,100px); //把元素水平移动 50 像素,垂直移动 100 像素 tran ...