以上是一个tcp以客户端开始发数数据给服务端,最后服务端返回数据给客户的图,以下代码最为关键的地方是在第一个server接收数据传给第二个client端时,要将当前server端的通道(ChannelHandlerContext)
传给第二个客户端,为客户端接返回给第一个客户端做准备。
一、创建服务端环境
NettyServer .java
package com.netty;
import com.util.ReadProperties;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.DelimiterBasedFrameDecoder;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;
import io.netty.handler.timeout.IdleStateHandler;
import io.netty.util.CharsetUtil;
import java.nio.charset.Charset;
import java.util.concurrent.TimeUnit;
/**
* NETTY服务
*/
public class NettyServer {
/**
* netty启动端口号
*/
private static final int port = ReadProperties.bindPort;
public static void main(String[] args) {
// 用于接受客户端连接的请求 (并没有处理请求)
NioEventLoopGroup bossGroup = new NioEventLoopGroup();
// 用于处理客户端连接的读写操作
NioEventLoopGroup workGroup = new NioEventLoopGroup();
// 用于创建我们的ServerBootstrap
ServerBootstrap serverBootstrap = new ServerBootstrap();
serverBootstrap.group(bossGroup, workGroup).channel(NioServerSocketChannel.class)
.childHandler(new ChannelInitializer<SocketChannel>() {
@Override
protected void initChannel(SocketChannel socketChannel) throws Exception {
socketChannel.pipeline().addLast(new IdleStateHandler(10, 0, 0, TimeUnit.SECONDS));
socketChannel.pipeline().addLast(new HeartBeatServerHandler());
// 解码器--负责将消息从字节或其他序列形式转成指定的消息对象
socketChannel.pipeline().addLast("decoder", new StringDecoder(CharsetUtil.UTF_8));
//编码器--将消息对象转成字节或其他序列形式在网络上传输
socketChannel.pipeline().addLast("encoder", new StringEncoder(CharsetUtil.UTF_8));
socketChannel.pipeline().addLast(new ServerHandler());
}
});
// 绑定我们的端口号码
try {
// 绑定端口号,同步等待成功
ChannelFuture future = serverBootstrap.bind(port).sync();
System.out.println("服务器启动成功...");
future.addListener((ChannelFutureListener) future1 -> {
if (future1.isSuccess()) {
System.out.println(port + "启动成功!");
} else {
System.out.println(port + "启动失败!");
}
});
// 等待服务器监听端口
future.channel().closeFuture().sync();
} catch (Exception e) {
e.printStackTrace();
} finally {
// 优雅的关闭连接
bossGroup.shutdownGracefully();
workGroup.shutdownGracefully();
}
}
}
ServerHandler .java
package com.netty;
import com.clien.NettyClient;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
public class ServerHandler extends SimpleChannelInboundHandler<String> {
@Override
protected void channelRead0(ChannelHandlerContext ctx, String data) throws Exception {
try {
new NettyClient("127.0.0.1", 7022, data,ctx).start();
} catch (Exception e) {
e.printStackTrace();
}
}
}
二、创建客户端环境
NettyClient .java
package com.clien;
import com.alibaba.fastjson.JSONObject;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.DelimiterBasedFrameDecoder;
import io.netty.handler.codec.Delimiters;
import io.netty.handler.codec.string.StringEncoder;
import io.netty.util.AttributeKey;
import java.util.Map;
/**
* Netty客户端编写
*
* @author Administrator
*/
public class NettyClient {
private String ip;
private int port;
private String data;
private ChannelHandlerContext ctx;//服务端通道
public NettyClient(String ip, int port, String data, ChannelHandlerContext ctx) {
this.ip = ip;
this.port = port;
this.data = data;
this.ctx = ctx;
}
public void start() throws InterruptedException {
Bootstrap client = new Bootstrap();
EventLoopGroup group = new NioEventLoopGroup();
client.group(group);
client.channel(NioSocketChannel.class);
client.handler(new ChannelInitializer<NioSocketChannel>() { //通道是NioSocketChannel
@Override
protected void initChannel(NioSocketChannel ch) throws Exception {
ch.pipeline().addLast(new StringEncoder());
ch.pipeline().addLast(new SimpleClientHandler(ctx));
}
});
//连接服务器
ChannelFuture future = client.connect(ip, port).sync();
//发送数据给服务器
future.channel().writeAndFlush(JSONObject.toJSONString(data));
future.channel().closeFuture().sync();
//接收服务端返回的数据
}
}
处理服务端返回的数据 SimpleClientHandler.java
package com.clien;
import io.netty.buffer.ByteBuf;
import io.netty.channel.*;
import io.netty.util.AttributeKey;
import java.nio.charset.Charset;
import java.util.Map;
/**
* 处理服务端返回的数据
*
* @author Administrator
*/
public class SimpleClientHandler extends ChannelInboundHandlerAdapter {
private ChannelHandlerContext context;
public SimpleClientHandler(ChannelHandlerContext context) {
this.context = context;
}
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
if (msg instanceof ByteBuf) {
String value = ((ByteBuf) msg).toString(Charset.defaultCharset());
context.writeAndFlush(value);
}
//把服务端的通道关闭
context.channel().close();
//把客户端的通道关闭
ctx.channel().close();
}
}