工程结构图

一、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. ipc$ 空连接 net use

    常用命令 [xxx]表示的内容,需要根据自己的需求更改 //建立空连接 > net use \\127.0.0.1\ipc$ //删除连接 > net use \\127.0.0.1\ip ...

  2. c++ 初始化静态static成员变量或static复合成员变量

    https://stackoverflow.com/questions/185844/how-to-initialize-private-static-members-in-c https://sta ...

  3. Linux文本处理三剑客之grep及正则表达式详解

    Linux文本处理三剑客之grep及正则表达式详解 作者:尹正杰 版权声明:原创作品,谢绝转载!否则将追究法律责任. 一.Linux文本处理三剑客概述 grep: 全称:"Global se ...

  4. tensorflow tfrecoder read write

    # write in tfrecord import tensorflow as tf import os os.environ[' FLAGS = tf.app.flags.FLAGS tf.app ...

  5. 划分土地(how many pieces of land)

    题目描述: 给一个椭圆,上面有n个点,两两连接这n个点,得到的线段能把椭圆分为几个区域? 思路: 首先想想,n个点在椭圆边缘,每两个点两两连接有\(C^2_n\)条线段,这些线段交于很多点,求这些线段 ...

  6. 算法- 求解最大平均值的子树-经典dfs题目

    给一棵二叉树,找到有最大平均值的子树.返回子树的根结点. Example 样例1 输入: {1,-5,11,1,2,4,-2} 输出:11 说明: 这棵树如下所示: 1 / \ -5 11 / \ / ...

  7. python学习类与方法的调用规则

    1类方法的特点是类方法不属于任何该类的对象,只属于类本身 2类的静态方法类似于全局函数,因为静态方法既没有实例方法的self参数也没有类方法的cls参数,谁都可以调用 3.实例方法只属于实例,是实例化 ...

  8. python——selenium库的使用

    selenium 是一个用于Web应用程序测试的工具.Selenium测试直接运行在浏览器中,就像真正的用户在操作一样.支持的浏览器包括IE(7, 8, 9, 10, 11),Mozilla Fire ...

  9. js里调用函数时,函数名带括号与不带括号的区别

    function test(){ return 1;}var a=test;console.log(a);//输出[Function: test]var b=test();console.log(b) ...

  10. 异常检测(Anomaly detection): 什么是异常检测及其一些应用

    异常检测的例子: 如飞机引擎的两个特征:产生热量与振动频率,我们有m个样本画在图中如上图的叉叉所示,这时来了一个新的样本(xtest),如果它落在上面,则表示它没有问题,如果它落在下面(如上图所示), ...