工程结构图

一、Socket服务端

1、创建MyServer 类

public class MyServer {
public static void main(String[] args) throws Exception{
EventLoopGroup bossGroup = new NioEventLoopGroup();
EventLoopGroup worderGroup = new NioEventLoopGroup();
try{ ServerBootstrap serverBootstrap = new ServerBootstrap();
serverBootstrap.group(bossGroup,worderGroup).channel(NioServerSocketChannel.class)
.childHandler(new MyServerinitializer()); ChannelFuture channelFuture = serverBootstrap.bind(8899).sync();
channelFuture.channel().closeFuture().sync();
}finally {
bossGroup.shutdownGracefully();
worderGroup.shutdownGracefully();
}
}
}

  

2、服务端处理器类MyServerHandle

public class MyServerHandle  extends SimpleChannelInboundHandler<String>{

    protected void channelRead0(ChannelHandlerContext ctx, String msg) throws Exception {
CommonUtil.println(ctx.channel().remoteAddress() + ", " + msg);
ctx.channel().writeAndFlush("from server: " + UUID.randomUUID());
} @Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
cause.printStackTrace();;
ctx.close();
}
}

  当接收到请求后,向客户端写数据。

3、创建MyServerinitializer类

public class MyServerinitializer  extends ChannelInitializer<SocketChannel>{

    protected void initChannel(SocketChannel socketChannel) throws Exception {
ChannelPipeline pipeline = socketChannel.pipeline();
pipeline.addLast(new LengthFieldBasedFrameDecoder(Integer.MAX_VALUE,0, 4, 0, 4));
pipeline.addLast(new LengthFieldPrepender(4));
pipeline.addLast(new StringDecoder(CharsetUtil.UTF_8));
pipeline.addLast(new StringEncoder(CharsetUtil.UTF_8));
pipeline.addLast(new MyServerHandle());
}
}

  

二、客户端

1、MyClient 类

public class MyClient {
public static void main(String[] args) throws Exception{
EventLoopGroup eventLoopGroup = new NioEventLoopGroup();
try {
Bootstrap bootstrap = new Bootstrap();
bootstrap.group(eventLoopGroup).channel(NioSocketChannel.class)
.handler(new MyClientInitializer()); ChannelFuture channelFuture = bootstrap.connect("localhost",8899).sync();
channelFuture.channel().closeFuture().sync();
}finally {
eventLoopGroup.shutdownGracefully();
}
}
}

  

2、客户端处理器MyClientHandle

public class MyClientHandle extends SimpleChannelInboundHandler<String> {

    //服务端向客户端发送消息时,该方法会被调用
@Override
protected void channelRead0(ChannelHandlerContext ctx, String msg) throws Exception {
CommonUtil.println(ctx.channel().remoteAddress());
CommonUtil.println("client output:" + msg);
ctx.writeAndFlush("from client: " + LocalDateTime.now());
} @Override
public void channelActive(ChannelHandlerContext ctx) throws Exception {
ctx.writeAndFlush("来自客户端的消息");
} @Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
cause.printStackTrace();
ctx.close();
}
}

  客户端channel active后,向服务端发送消息

3、MyClientInitializer类

public class MyClientInitializer  extends ChannelInitializer<SocketChannel> {

    protected void initChannel(SocketChannel ch) throws Exception {
ChannelPipeline pipeline = ch.pipeline();
pipeline.addLast(new LengthFieldBasedFrameDecoder(Integer.MAX_VALUE,0, 4, 0, 4));
pipeline.addLast(new LengthFieldPrepender(4));
pipeline.addLast(new StringDecoder(CharsetUtil.UTF_8));
pipeline.addLast(new StringEncoder(CharsetUtil.UTF_8));
pipeline.addLast(new MyClientHandle());
}
}

  

三、测试

1、启动服务端

2、启动客户端(可以启动多个)

服务端输出结果

客户端1输出

客户端2输出

Netty Socket编程的更多相关文章

  1. IO和socket编程

    五一假期结束了,突然想到3周前去上班的路上看到槐花开的正好.放假也没能采些做槐花糕,到下周肯定就老了.一年就开一次的东西,比如牡丹,花期也就一周.而花开之时,玫瑰和月季无法与之相比.明日黄花蝶也愁.想 ...

  2. Netty高性能编程备忘录(上)

    http://calvin1978.blogcn.com/articles/netty-performance.html 网上赞扬Netty高性能的文章不要太多,但如何利用Netty写出高性能网络应用 ...

  3. Linux下的C Socket编程 -- server端的继续研究

    Linux下的C Socket编程(四) 延长server的生命周期 在前面的一个个例子中,server在处理完一个连接后便会立即结束掉自己,然而这种server并不科学啊,server应该是能够一直 ...

  4. java socket编程(li)

    一.网络编程中两个主要的问题 一个是如何准确的定位网络上一台或多台主机,另一个就是找到主机后如何可靠高效的进行数据传输.在TCP/IP协议中IP层主要负责网络主机的定位,数据传输的路由,由IP地址可以 ...

  5. Python Socket 编程——聊天室示例程序

    上一篇 我们学习了简单的 Python TCP Socket 编程,通过分别写服务端和客户端的代码了解基本的 Python Socket 编程模型.本文再通过一个例子来加强一下对 Socket 编程的 ...

  6. Linux下的C Socket编程 -- server端的简单示例

    Linux下的C Socket编程(三) server端的简单示例 经过前面的client端的学习,我们已经知道了如何创建socket,所以接下来就是去绑定他到具体的一个端口上面去. 绑定socket ...

  7. Linux下的C Socket编程 -- 获取对方IP地址

    Linux下的C Socket编程(二) 获取域名对应的IP地址 经过上面的讨论,如果我们想要连接到远程的服务器,我们需要知道对方的IP地址,系统函数gethostbyname便能够实现这个目的.它能 ...

  8. Linux下的C Socket编程 -- 简介与client端的处理

    Linux下的C Socket编程(一) 介绍 Socket是进程间通信的方式之一,是进程间的通信.这里说的进程并不一定是在同一台机器上也有可能是通过网络连接的不同机器上.只要他们之间建立起了sock ...

  9. python网络编程-socket编程

     一.服务端和客户端 BS架构 (腾讯通软件:server+client) CS架构 (web网站) C/S架构与socket的关系: 我们学习socket就是为了完成C/S架构的开发 二.OSI七层 ...

随机推荐

  1. ResourceDictionary文件排序方法

    默认生成的ResourceDictionary文件是根据主键的hashcode排序生成的,如果想按主键排序生成是不可能的. 可以使用Xml的处理方法来生成ResourceDictionary文件. 1 ...

  2. JWT生成token及过期处理方案

    业务场景 在前后分离场景下,越来越多的项目使用token作为接口的安全机制,APP端或者WEB端(使用VUE.REACTJS等构建)使用token与后端接口交互,以达到安全的目的.本文结合stacko ...

  3. MavenWrapper替代Maven

    1. 说明 jdk8已经安装成功 Maven已经安装成功 参见Maven Wrapper 2. Maven初始化项目 注:初次执行,Maven会下载很多jar,需等待几分钟 mvn archetype ...

  4. 【异常(待解决)】org.apache.http.NoHttpResponseException: api.weixin.qq.com:443 failed to respond

    一.记录下异常堆栈信息 -- ::-exec-] ERROR weixin.popular.client.LocalHttpClient - execute error org.apache.http ...

  5. docker 安装 oracle

    docker 安装 oracle 部署链接:https://www.linuxidc.com/Linux/2017-03/141760.htm 本次使用docker安装oracle 1.搜索可使用的镜 ...

  6. vue2 design 手记

    Ant Design of Vue github地址:https://github.com/vueComponent/ant-design-vue Ant Design of Vue文档:https: ...

  7. MySQL/MariaDB数据库的主主复制

      MySQL/MariaDB数据库的主主复制 作者:尹正杰  版权声明:原创作品,谢绝转载!否则将追究法律责任. 一.主主复制概述 1>.什么是主主复制 所谓的主主复制,说白了就是两台节点互为 ...

  8. typeScript学习随笔(一)

    TypeScript学习随笔(一) 这么久了还不没好好学习哈这么火的ts,边学边练边记吧! 啥子是TypeScript  TypeScript 是 JavaScript 的一个超集,支持 es6 标准 ...

  9. python面试题&练习题之运算符与if控制

    1.任意的输入10个数字,按从大到小排序 l2 = [] for i in range(1,11): num = input('输入第{}个数字'.format(i)) if num.isdigit( ...

  10. [转]windows10下安装与激活rational rose 2003

    Rational Rose2003安装+激活教程(Win10)(另附安装包+激活软件) 原文链接:https://blog.csdn.net/qq_38388811/article/details/8 ...