netty4.0之TCP的server与client初探(与3.X版本变化)DEMO
来源:互联网 发布:shell和python 编辑:程序博客网 时间:2024/05/21 12:02
(2)TcpServerHandler.javapackage com.lin.netty4.tcp;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.LengthFieldBasedFrameDecoder;
import io.netty.handler.codec.LengthFieldPrepender;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;
import io.netty.util.CharsetUtil;
import org.apache.log4j.Logger;
public class TcpServer {
private static final Logger logger = Logger.getLogger(TcpServer.class);
private static final String IP = "127.0.0.1";
private static final int PORT = 9999;
/**用于分配处理业务线程的线程组个数 */
protected static final int BIZGROUPSIZE = Runtime.getRuntime().availableProcessors()*2;//默认
/** 业务出现线程大小*/
protected static final int BIZTHREADSIZE = 4;
private static final EventLoopGroup bossGroup = new NioEventLoopGroup(BIZGROUPSIZE);
private static final EventLoopGroup workerGroup = new NioEventLoopGroup(BIZTHREADSIZE);
protected static void run() throws Exception {
ServerBootstrap b = new ServerBootstrap();
b.group(bossGroup, workerGroup);
b.channel(NioServerSocketChannel.class);
b.childHandler(new ChannelInitializer<SocketChannel>() {
@Override
public void initChannel(SocketChannel ch) throws Exception {
ChannelPipeline pipeline = ch.pipeline();
pipeline.addLast("frameDecoder", new LengthFieldBasedFrameDecoder(Integer.MAX_VALUE, 0, 4, 0, 4));
pipeline.addLast("frameEncoder", new LengthFieldPrepender(4));
pipeline.addLast("decoder", new StringDecoder(CharsetUtil.UTF_8));
pipeline.addLast("encoder", new StringEncoder(CharsetUtil.UTF_8));
pipeline.addLast(new TcpServerHandler());
}
});
b.bind(IP, PORT).sync();
logger.info("TCP服务器已启动");
}
protected static void shutdown() {
workerGroup.shutdownGracefully();
bossGroup.shutdownGracefully();
}
public static void main(String[] args) throws Exception {
logger.info("开始启动TCP服务器...");
TcpServer.run();
//TcpServer.shutdown();
}
}
package com.lin.netty4.tcp;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import org.apache.log4j.Logger;
public class TcpServerHandler extends SimpleChannelInboundHandler<Object> {
private static final Logger logger = Logger.getLogger(TcpServerHandler.class);
@Override
public void channelRead0(ChannelHandlerContext ctx, Object msg) throws Exception {
logger.info("SERVER接收到消息:"+msg);
ctx.channel().writeAndFlush("yes, server is accepted you ,nice !"+msg);
}
@Override
public void exceptionCaught(ChannelHandlerContext ctx,
Throwable cause) throws Exception {
logger.warn("Unexpected exception from downstream.", cause);
ctx.close();
}
}
(3)
(4)TcpClientHandler.javapackage com.lin.netty4.tcp;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.LengthFieldBasedFrameDecoder;
import io.netty.handler.codec.LengthFieldPrepender;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;
import io.netty.util.CharsetUtil;
import org.apache.log4j.Logger;
public class TcpClient {
private static final Logger logger = Logger.getLogger(TcpClient.class);
public static String HOST = "127.0.0.1";
public static int PORT = 9999;
public static Bootstrap bootstrap = getBootstrap();
public static Channel channel = getChannel(HOST,PORT);
/**
* 初始化Bootstrap
* @return
*/
public static final Bootstrap getBootstrap(){
EventLoopGroup group = new NioEventLoopGroup();
Bootstrap b = new Bootstrap();
b.group(group).channel(NioSocketChannel.class);
b.handler(new ChannelInitializer<Channel>() {
@Override
protected void initChannel(Channel ch) throws Exception {
ChannelPipeline pipeline = ch.pipeline();
pipeline.addLast("frameDecoder", new LengthFieldBasedFrameDecoder(Integer.MAX_VALUE, 0, 4, 0, 4));
pipeline.addLast("frameEncoder", new LengthFieldPrepender(4));
pipeline.addLast("decoder", new StringDecoder(CharsetUtil.UTF_8));
pipeline.addLast("encoder", new StringEncoder(CharsetUtil.UTF_8));
pipeline.addLast("handler", new TcpClientHandler());
}
});
b.option(ChannelOption.SO_KEEPALIVE, true);
return b;
}
public static final Channel getChannel(String host,int port){
Channel channel = null;
try {
channel = bootstrap.connect(host, port).sync().channel();
} catch (Exception e) {
logger.error(String.format("连接Server(IP[%s],PORT[%s])失败", host,port),e);
return null;
}
return channel;
}
public static void sendMsg(String msg) throws Exception {
if(channel!=null){
channel.writeAndFlush(msg).sync();
}else{
logger.warn("消息发送失败,连接尚未建立!");
}
}
public static void main(String[] args) throws Exception {
try {
long t0 = System.nanoTime();
for (int i = 0; i < 100000; i++) {
TcpClient.sendMsg(i+"你好1");
}
long t1 = System.nanoTime();
System.out.println((t1-t0)/1000000.0);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
package com.lin.netty4.tcp;
import org.apache.log4j.Logger;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
public class TcpClientHandler extends SimpleChannelInboundHandler<Object> {
private static final Logger logger = Logger.getLogger(TcpClientHandler.class);
@Override
protected void channelRead0(ChannelHandlerContext ctx, Object msg)
throws Exception {
//messageReceived方法,名称很别扭,像是一个内部方法.
logger.info("client接收到服务器返回的消息:"+msg);
}
}
- netty4.0之TCP的server与client初探(与3.X版本变化)DEMO
- netty4.0之TCP的server与client初探(与3.X版本变化)DEMO
- Netty4.0学习笔记系列之一:Server与Client的通讯
- Netty4.0学习笔记系列之一:Server与Client的通讯
- Netty4.0学习笔记系列之一:Server与Client的通讯
- Netty4.0学习笔记系列之一:Server与Client的通讯
- Netty4.0学习笔记系列之一:Server与Client的通讯
- Netty4.0学习笔记系列之一:Server与Client的通讯
- Netty4.0学习笔记系列之一:Server与Client的通讯
- Netty4.0学习笔记系列之一:Server与Client的通讯
- Netty4.0学习笔记系列之一:Server与Client的通讯
- Netty4.0学习笔记系列之一:Server与Client的通讯
- Tcp Client与Server 基本原理
- netty4 tcp与protobuf3的整合使用。
- Netty4 学习笔记之二:客户端与服务端心跳 demo
- Qt下Client与Server之间的双向TCP通信。
- Qt下Client与Server之间的双向TCP通信。
- Netty4.0的DefaultHttpRequest与FullHttpRequest
- Linux Top 命令解析
- JVM调优总结 -Xms -Xmx -Xmn -Xss
- JVM(Java虚拟机)优化大全和案例实战
- Linux时间类型、函数和休眠函数
- oracle报错:java.sql.SQLException: An attempt by a client to checkout a Connection has timed out
- netty4.0之TCP的server与client初探(与3.X版本变化)DEMO
- 关于UDP数据传输中出现的分包问题的一点解释
- droools学习入门
- itpub索引树,都是精华
- 基于netty4的TCP短连接测试
- 执行安装redis报错undefined reference to `__sync_add_and_fetch_4\'
- json-lib 与Jackson性能对比
- 有关NoSQL的一点理论知识
- 关于ByteBuffer的一些知识