前面一文说了 基于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. OutputFormat---自定义输出方式

    简介 可以自定义输出的格式和文件,例如包含某字段的输出到一个指定文件,不包含某字段的输出到另一个文件. 案例 数据 www.nevesettle.com www.baidu.com www.qq.co ...

  2. 自动化运维工具之Puppet master/agent模型、站点清单和puppet多环境设定

    前文我们了解了puppe中模块的使用,回顾请参考https://www.cnblogs.com/qiuhom-1874/p/14086315.html:今天我来了解下puppet的master/age ...

  3. git 常用命令 command 1.0(本地 local repository 对远程仓库 remote repository 的操作)

     输入 q 退出 日志界面

  4. POJ2466 棋盘覆盖

    一张\(n*m\)的棋盘,有\(k\)个点不能被覆盖,问其余点能不能被\(1*2\)的小矩形完全覆盖,多测 这题先输入\(m\)是什么鬼啊!!! 其实是一个比较裸的二分图判定,把\(k\)个点挖去然后 ...

  5. 升级jenkins之后无法启动 报错Unable to read /var/lib/jenkins/config.xml

    故障记录 点击jenkins升级后再点击回滚到之前版本,jenkins就起不来了. 欲哭无泪,报错如下 hudson.util.HudsonFailedToLoad: org.jvnet.hudson ...

  6. 洛谷题解 P1051 【谁拿了最多奖学金】

    其实很水 链接: P1051 [谁拿了最多奖学金] 注意: 看好信息,不要看漏或看错因为信息很密集 AC代码: 1 #include<bits/stdc++.h>//头文件 2 using ...

  7. Spark-2-性能监控方式

    1 Spark Web UI Spark提供了一些基本的Web监控页面,对于日常监控十分有用. 通过http://master:4040(默认端口是4040,可以通过spark.ui.port修改)我 ...

  8. Numpy的学习6-深浅赋值(copy&deep copy)

    # = 的赋值方式会带有关联性 import numpy as np a = np.arange(4) # array([0, 1, 2, 3]) b = a c = a d = b # 改变a的第一 ...

  9. sqoop用法之mysql与hive数据导入导出

    目录 一. Sqoop介绍 二. Mysql 数据导入到 Hive 三. Hive数据导入到Mysql 四. mysql数据增量导入hive 1. 基于递增列Append导入 1). 创建hive表 ...

  10. C#中string类型必填的诡异问题

    背景 ASP.NETCore3.0项目,使用Swagger接口文档. 之前的项目都是Swashbuckle.AspNetCore-5.0.0 新项目想尝尝鲜,用最新版Swashbuckle.AspNe ...