Netty: Socket: a demo

这篇博客详细介绍了使用Netty进行Socket通信的三个不同示例,包括First Server、Second Server和Third Server。每个示例都包含了客户端和服务器端的实现,涉及到DTO(Data Transfer Object)的设计,如TransportObject.java,以及客户端和服务器的Handler类。博主还提供了完整的操作流程和各个阶段的输出结果,便于读者理解和复现。源码已上传至GitHub,供读者下载参考。

Netty: Socket: a demo


DTO

TransportObject.java

package com.me.dto;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

public class TransportObject implements Serializable {

    private String name;
    private int id;
    private List<String> list = new ArrayList<String>();

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public List<String> getList() {
        return list;
    }

    public void setList(List<String> list) {
        this.list = list;
    }

    @Override
    public String toString() {
        return "{" +
                "name='" + name + '\'' +
                ", id=" + id +
                ", list=" + list +
                '}';
    }

}


First Server

FirstClient.java

package com.me.socket.client;

import com.me.dto.TransportObject;
import io.netty.bootstrap.Bootstrap;
import io.netty.buffer.Unpooled;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.bytes.ByteArrayEncoder;
import io.netty.handler.codec.string.StringEncoder;
import io.netty.handler.stream.ChunkedWriteHandler;
import io.netty.util.CharsetUtil;

import java.net.InetSocketAddress;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.List;

public class FirstClient {

    private final String host;
    private final int port;

    public FirstClientHandler cl=new FirstClientHandler();

    public FirstClient() {
        this(0);
    }

    public FirstClient(int port) {
        this("localhost", port);
    }

    public FirstClient(String host, int port) {
        this.host = host;
        this.port = port;
    }

    public void connect(String msg) throws Exception {
        EventLoopGroup group = new NioEventLoopGroup();
        try {
            Bootstrap b = new Bootstrap();
            b.group(group) // 注册线程池
                    .channel(NioSocketChannel.class) // 使用NioSocketChannel来作为连接用的channel类
                    .remoteAddress(new InetSocketAddress(this.host, this.port)) // 绑定连接端口和host信息
                    .handler(new ChannelInitializer<SocketChannel>() { // 绑定连接初始化器
                        @Override
                        protected void initChannel(SocketChannel ch) throws Exception {
                            System.out.println("--------------------client: channel log begin--------------------");
                            System.out.println("正在连接中...");
                            ch.pipeline().addLast(new StringEncoder(Charset.forName("GBK")));
//                            ch.pipeline().addLast(new FirstClientHandler());
                            ch.pipeline().addLast(cl);
                            ch.pipeline().addLast(new ByteArrayEncoder());
                            ch.pipeline().addLast(new ChunkedWriteHandler());

                        }
                    });
            // System.out.println("服务端连接成功..");

            ChannelFuture cf = b.connect().sync(); // 异步连接服务器
            System.out.println("服务端连接成功..."); // 连接完成

//            channel = cf.channel();

            cl.myctx.writeAndFlush(Unpooled.copiedBuffer(msg, CharsetUtil.UTF_8)); // 必须有flush

            cf.channel().closeFuture().sync(); // 异步等待关闭连接channel
            System.out.println("连接已关闭.."); // 关闭完成

        } finally {
            group.shutdownGracefully().sync(); // 释放线程池资源
        }
    }

    public static void main(String[] args) throws Exception {

        TransportObject data = new TransportObject();
        data.setId(999);
        data.setName("xyz");
        List<String> list = new ArrayList<String>();
        list.add("111");
        list.add("222");
        list.add("333");
        data.setList(list);

        // 8882: second-server, transfer data to second-server
        FirstClient firstClient = new FirstClient("127.0.0.1", 8882);
        firstClient.connect(data.toString());

        System.out.println("=========================");

    }
}

FirstClientHandler.java

package com.me.socket.client;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.ByteBufUtil;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;

import java.nio.charset.Charset;

public class FirstClientHandler extends SimpleChannelInboundHandler<ByteBuf> {

    public ChannelHandlerContext myctx;

    /**
     * 向服务端发送数据
     */
    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        myctx=ctx;

        System.out.println("客户端与服务端通道-开启:" + ctx.channel().localAddress() + "channelActive");

//        String sendInfo = "Hello 这里是first客户端  你好啊!";
//        System.out.println("客户端准备发送的数据包:" + sendInfo);
//        ctx.writeAndFlush(Unpooled.copiedBuffer(sendInfo, CharsetUtil.UTF_8)); // 必须有flush

    }

    /**
     * channelInactive
     *
     * channel 通道 Inactive 不活跃的
     *
     * 当客户端主动断开服务端的链接后,这个通道就是不活跃的。也就是说客户端与服务端的关闭了通信通道并且不可以传输数据
     *
     */
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        System.out.println("客户端与服务端通道-关闭:" + ctx.channel().localAddress() + "channelInactive");
        System.out.println("--------------------client: channel log end--------------------");
    }

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, ByteBuf msg) throws Exception {
        System.out.println("读取客户端通道信息..");
        ByteBuf buf = msg.readBytes(msg.readableBytes());
        System.out.println(
                "客户端接收到的服务端信息:" + ByteBufUtil.hexDump(buf) + "; 数据包为:" + buf.toString(Charset.forName("utf-8")));
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        ctx.close();
        System.out.println("异常退出:" + cause.getMessage());
    }
}

FirstServer.java

package com.me.socket.server;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
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.bytes.ByteArrayEncoder;
import io.netty.handler.codec.string.StringEncoder;

import java.nio.charset.Charset;

public class FirstServer {
    private final int port;

    public FirstServer(int port) {
        this.port = port;
    }

    public void connect() throws Exception {
        EventLoopGroup bossGroup = new NioEventLoopGroup();

        EventLoopGroup group = new NioEventLoopGroup();
        try {
            ServerBootstrap sb = new ServerBootstrap();
            sb.option(ChannelOption.SO_BACKLOG, 1024);
            sb.group(group, bossGroup) // 绑定线程池
                    .channel(NioServerSocketChannel.class) // 指定使用的channel
                    .localAddress(this.port)// 绑定监听端口
                    .childHandler(new ChannelInitializer<SocketChannel>() { // 绑定客户端连接时候触发操作

                        @Override
                        protected void initChannel(SocketChannel ch) throws Exception {
                            System.out.println("--------------------server: channel log begin--------------------");
                            System.out.println("报告");
                            System.out.println("信息:有一客户端链接到本服务端");
//                            System.out.println("IP:" + ch.localAddress().getHostName());
                            System.out.println("IP:" + ch.remoteAddress().getHostName());
//                            System.out.println("Port:" + ch.localAddress().getPort());
                            System.out.println("Port:" + ch.remoteAddress().getPort());
                            System.out.println("报告完毕");

                            ch.pipeline().addLast(new StringEncoder(Charset.forName("GBK")));
                            ch.pipeline().addLast(new FirstServerHandler()); // 客户端触发操作
                            ch.pipeline().addLast(new ByteArrayEncoder());
                        }
                    });
            ChannelFuture cf = sb.bind().sync(); // 服务器异步创建绑定
            System.out.println(FirstServer.class + " 启动正在监听: " + cf.channel().localAddress());
            cf.channel().closeFuture().sync(); // 关闭服务器通道
        } finally {
            group.shutdownGracefully().sync(); // 释放线程池资源
            bossGroup.shutdownGracefully().sync();
        }
    }

    public static void main(String[] args) throws Exception {

        new FirstServer(8881).connect(); // 启动
    }
}

FirstServerHandler.java

package com.me.socket.server;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;

import java.io.UnsupportedEncodingException;

public class FirstServerHandler extends ChannelInboundHandlerAdapter {

    /**
     * channelAction
     *
     * channel 通道 action 活跃的
     *
     * 当客户端主动链接服务端的链接后,这个通道就是活跃的了。也就是客户端与服务端建立了通信通道并且可以传输数据
     *
     */
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        System.out.println(ctx.channel().localAddress().toString() + " 通道已激活!");
    }

    /**
     * channelInactive
     *
     * channel 通道 Inactive 不活跃的
     *
     * 当客户端主动断开服务端的链接后,这个通道就是不活跃的。也就是说客户端与服务端的关闭了通信通道并且不可以传输数据
     *
     */
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        System.out.println(ctx.channel().localAddress().toString() + " 通道不活跃!");
        // 关闭流
        System.out.println("--------------------server: channel log end--------------------");

    }

    /**
     * TODO  此处用来处理收到的数据中含有中文的时  出现乱码的问题
     * @param buf
     * @return
     */
    private String getMessage(ByteBuf buf) {
        byte[] con = new byte[buf.readableBytes()];
        buf.readBytes(con);
        try {
            return new String(con, "UTF-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
            return null;
        }
    }

    /**
     * 功能:读取客户端发送过来的信息
     */
    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        // 第一种:接收字符串时的处理
        ByteBuf buf = (ByteBuf) msg;
        String rev = getMessage(buf);
        System.out.println("客户端收到服务器数据:" + rev);

    }

    /**
     * 功能:读取完毕客户端发送过来的数据之后的操作
     */
    @Override
    public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
        System.out.println("服务端接收数据完毕..");
        // 第一种方法:写一个空的buf,并刷新写出区域。完成后关闭sock channel连接。
        // after this line finished, 'cf.channel().closeFuture().sync();' in FirstClient will be executed.
        ctx.writeAndFlush(Unpooled.EMPTY_BUFFER).addListener(ChannelFutureListener.CLOSE);
//        ctx.writeAndFlush(Unpooled.copiedBuffer("Success", CharsetUtil.UTF_8));
        // ctx.flush();
        // ctx.flush(); //
        // 第二种方法:在client端关闭channel连接,这样的话,会触发两次channelReadComplete方法。
        // ctx.flush().close().sync(); // 第三种:改成这种写法也可以,但是这中写法,没有第一种方法的好。
    }

    /**
     * 功能:服务端发生异常的操作
     */
    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        ctx.close();
        System.out.println("异常信息:\r\n" + cause.getMessage());
    }
}


Second Server

SecondClient.java

package com.me.socket.client;

import io.netty.bootstrap.Bootstrap;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.bytes.ByteArrayEncoder;
import io.netty.handler.codec.string.StringEncoder;
import io.netty.handler.stream.ChunkedWriteHandler;
import io.netty.util.CharsetUtil;

import java.net.InetSocketAddress;
import java.nio.charset.Charset;

public class SecondClient {
    private final String host;
    private final int port;

    public SecondClientHandler cl=new SecondClientHandler();

    public SecondClient() {
        this(0);
    }

    public SecondClient(int port) {
        this("localhost", port);
    }

    public SecondClient(String host, int port) {
        this.host = host;
        this.port = port;
    }

    public void connect(String msg) throws Exception {
        EventLoopGroup group = new NioEventLoopGroup();
        try {
            Bootstrap b = new Bootstrap();
            b.group(group) // 注册线程池
                    .channel(NioSocketChannel.class) // 使用NioSocketChannel来作为连接用的channel类
                    .remoteAddress(new InetSocketAddress(this.host, this.port)) // 绑定连接端口和host信息
                    .handler(new ChannelInitializer<SocketChannel>() { // 绑定连接初始化器
                        @Override
                        protected void initChannel(SocketChannel ch) throws Exception {
                            System.out.println("--------------------client: channel log begin--------------------");
                            System.out.println("正在连接中...");
                            ch.pipeline().addLast(new StringEncoder(Charset.forName("GBK")));
//                            ch.pipeline().addLast(new SecondClientHandler());
                            ch.pipeline().addLast(cl);
                            ch.pipeline().addLast(new ByteArrayEncoder());
                            ch.pipeline().addLast(new ChunkedWriteHandler());

                        }
                    });
            // System.out.println("服务端连接成功..");

            ChannelFuture cf = b.connect().sync(); // 异步连接服务器
            System.out.println("服务端连接成功..."); // 连接完成

            cl.myctx.writeAndFlush(Unpooled.copiedBuffer(msg, CharsetUtil.UTF_8)); // 必须有flush

            cf.channel().closeFuture().sync(); // 异步等待关闭连接channel
            System.out.println("连接已关闭.."); // 关闭完成

        } finally {
            group.shutdownGracefully().sync(); // 释放线程池资源
        }
    }

    public static void main(String[] args) throws Exception {

        new SecondClient("127.0.0.1", 8888).connect("second msg"); // 连接127.0.0.1/65535,并启动

    }
}

SecondClientHandler.java

package com.me.socket.client;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.ByteBufUtil;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;

import java.nio.charset.Charset;

public class SecondClientHandler extends SimpleChannelInboundHandler<ByteBuf> {

    public ChannelHandlerContext myctx;

    /**
     * 向服务端发送数据
     */
    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        myctx = ctx;

        System.out.println("客户端与服务端通道-开启:" + ctx.channel().localAddress() + "channelActive");

//        String sendInfo = "Hello 这里是second客户端  你好啊!";
//        System.out.println("客户端准备发送的数据包:" + sendInfo);
//        ctx.writeAndFlush(Unpooled.copiedBuffer(sendInfo, CharsetUtil.UTF_8)); // 必须有flush

    }

    /**
     * channelInactive
     *
     * channel 通道 Inactive 不活跃的
     *
     * 当客户端主动断开服务端的链接后,这个通道就是不活跃的。也就是说客户端与服务端的关闭了通信通道并且不可以传输数据
     *
     */
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        System.out.println("客户端与服务端通道-关闭:" + ctx.channel().localAddress() + "channelInactive");
        System.out.println("--------------------client: channel log end--------------------");
    }

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, ByteBuf msg) throws Exception {
        System.out.println("读取客户端通道信息..");
        ByteBuf buf = msg.readBytes(msg.readableBytes());
        System.out.println(
                "客户端接收到的服务端信息:" + ByteBufUtil.hexDump(buf) + "; 数据包为:" + buf.toString(Charset.forName("utf-8")));
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        ctx.close();
        System.out.println("异常退出:" + cause.getMessage());
    }
}

SecondServer.java

package com.me.socket.server;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
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.bytes.ByteArrayEncoder;
import io.netty.handler.codec.string.StringEncoder;

import java.nio.charset.Charset;

public class SecondServer {
    private final int port;

    public SecondServer(int port) {
        this.port = port;
    }

    public void start() throws Exception {
        EventLoopGroup bossGroup = new NioEventLoopGroup();

        EventLoopGroup group = new NioEventLoopGroup();
        try {
            ServerBootstrap sb = new ServerBootstrap();
            sb.option(ChannelOption.SO_BACKLOG, 1024);
            sb.group(group, bossGroup) // 绑定线程池
                    .channel(NioServerSocketChannel.class) // 指定使用的channel
                    .localAddress(this.port)// 绑定监听端口
                    .childHandler(new ChannelInitializer<SocketChannel>() { // 绑定客户端连接时候触发操作

                        @Override
                        protected void initChannel(SocketChannel ch) throws Exception {
                            System.out.println("--------------------server: channel log begin--------------------");
                            System.out.println("报告");
                            System.out.println("信息:有一客户端链接到本服务端");
//                            System.out.println("IP:" + ch.localAddress().getHostName());
                            System.out.println("IP:" + ch.remoteAddress().getHostName());
//                            System.out.println("Port:" + ch.localAddress().getPort());
                            System.out.println("Port:" + ch.remoteAddress().getPort());
                            System.out.println("报告完毕");

                            ch.pipeline().addLast(new StringEncoder(Charset.forName("GBK")));
                            ch.pipeline().addLast(new SecondServerHandler()); // 客户端触发操作
                            ch.pipeline().addLast(new ByteArrayEncoder());
                        }
                    });
            ChannelFuture cf = sb.bind().sync(); // 服务器异步创建绑定
            System.out.println(SecondServer.class + " 启动正在监听: " + cf.channel().localAddress());
            cf.channel().closeFuture().sync(); // 关闭服务器通道
        } finally {
            group.shutdownGracefully().sync(); // 释放线程池资源
            bossGroup.shutdownGracefully().sync();
        }
    }

    public static void main(String[] args) throws Exception {

        new SecondServer(8882).start(); // 启动
    }
}

SecondServerHandler.java

package com.me.socket.server;

import com.me.dto.TransportObject;
import com.me.socket.client.SecondClient;
import com.google.gson.Gson;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;

import java.io.UnsupportedEncodingException;

public class SecondServerHandler extends ChannelInboundHandlerAdapter {

    private String rev;

    /**
     * channelAction
     *
     * channel 通道 action 活跃的
     *
     * 当客户端主动链接服务端的链接后,这个通道就是活跃的了。也就是客户端与服务端建立了通信通道并且可以传输数据
     *
     */
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        System.out.println(ctx.channel().localAddress().toString() + " 通道已激活!");
    }

    /**
     * channelInactive
     *
     * channel 通道 Inactive 不活跃的
     *
     * 当客户端主动断开服务端的链接后,这个通道就是不活跃的。也就是说客户端与服务端的关闭了通信通道并且不可以传输数据
     *
     */
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        System.out.println(ctx.channel().localAddress().toString() + " 通道不活跃!");
        // 关闭流

        System.out.println("--------------------server: channel log end--------------------");
    }

    /**
     * TODO  此处用来处理收到的数据中含有中文的时  出现乱码的问题
     * @param buf
     * @return
     */
    private String getMessage(ByteBuf buf) {
        byte[] con = new byte[buf.readableBytes()];
        buf.readBytes(con);
        try {
            return new String(con, "UTF-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
            return null;
        }
    }

    /**
     * 功能:读取first-server发送过来的信息
     */
    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        // 第一种:接收字符串时的处理
        ByteBuf buf = (ByteBuf) msg;
//        String rev = getMessage(buf);
        rev = getMessage(buf);
        System.out.println("second-server收到first-server发送的数据:" + rev);

    }

    /**
     * 功能:读取完毕客户端发送过来的数据之后的操作
     */
    @Override
    public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
        System.out.println("服务端接收数据完毕..");
        // 第一种方法:写一个空的buf,并刷新写出区域。完成后关闭sock channel连接。
        ctx.writeAndFlush(Unpooled.EMPTY_BUFFER).addListener(ChannelFutureListener.CLOSE);

        // 数据处理 Gson解析json
        TransportObject transportObject = new Gson().fromJson(rev, TransportObject.class);
        transportObject.getList().add("444");
        transportObject.setName("当前位置second");
        transportObject.setId(888);

        // 数据传输 transfer data to 8883: third-server
        SecondClient secondClient = new SecondClient("127.0.0.1", 8883);
        // data to send after operations
        secondClient.connect(transportObject.toString()+" | second msg");

//        ctx.writeAndFlush(Unpooled.copiedBuffer("Success", CharsetUtil.UTF_8));
        // ctx.flush();
        // ctx.flush(); //
        // 第二种方法:在client端关闭channel连接,这样的话,会触发两次channelReadComplete方法。
        // ctx.flush().close().sync(); // 第三种:改成这种写法也可以,但是这中写法,没有第一种方法的好。
    }

    /**
     * 功能:服务端发生异常的操作
     */
    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        ctx.close();
        System.out.println("异常信息:\r\n" + cause.getMessage());
    }
}


Third Server

ThirdClient.java

package com.me.socket.client;

import io.netty.bootstrap.Bootstrap;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.bytes.ByteArrayEncoder;
import io.netty.handler.codec.string.StringEncoder;
import io.netty.handler.stream.ChunkedWriteHandler;
import io.netty.util.CharsetUtil;

import java.net.InetSocketAddress;
import java.nio.charset.Charset;

public class ThirdClient {
    private final String host;
    private final int port;

    public ThirdClientHandler cl=new ThirdClientHandler();

    public ThirdClient() {
        this(0);
    }

    public ThirdClient(int port) {
        this("localhost", port);
    }

    public ThirdClient(String host, int port) {
        this.host = host;
        this.port = port;
    }

    public void connect(String msg) throws Exception {
        EventLoopGroup group = new NioEventLoopGroup();
        try {
            Bootstrap b = new Bootstrap();
            b.group(group) // 注册线程池
                    .channel(NioSocketChannel.class) // 使用NioSocketChannel来作为连接用的channel类
                    .remoteAddress(new InetSocketAddress(this.host, this.port)) // 绑定连接端口和host信息
                    .handler(new ChannelInitializer<SocketChannel>() { // 绑定连接初始化器
                        @Override
                        protected void initChannel(SocketChannel ch) throws Exception {
                            System.out.println("--------------------client: channel log begin--------------------");
                            System.out.println("正在连接中...");
                            ch.pipeline().addLast(new StringEncoder(Charset.forName("GBK")));
//                            ch.pipeline().addLast(new ThirdClientHandler());
                            ch.pipeline().addLast(cl);
                            ch.pipeline().addLast(new ByteArrayEncoder());
                            ch.pipeline().addLast(new ChunkedWriteHandler());

                        }
                    });
            // System.out.println("服务端连接成功..");

            ChannelFuture cf = b.connect().sync(); // 异步连接服务器
            System.out.println("服务端连接成功..."); // 连接完成

            cl.myctx.writeAndFlush(Unpooled.copiedBuffer(msg, CharsetUtil.UTF_8)); // 必须有flush

            cf.channel().closeFuture().sync(); // 异步等待关闭连接channel
            System.out.println("连接已关闭.."); // 关闭完成

        } finally {
            group.shutdownGracefully().sync(); // 释放线程池资源
        }
    }

    public static void main(String[] args) throws Exception {

        new ThirdClient("127.0.0.1", 8888).connect("aaa"); // 连接127.0.0.1/65535,并启动

    }
}

ThirdClientHandler.java

package com.me.socket.client;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.ByteBufUtil;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;

import java.nio.charset.Charset;

public class ThirdClientHandler extends SimpleChannelInboundHandler<ByteBuf> {

    public ChannelHandlerContext myctx;

    /**
     * 向服务端发送数据
     */
    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {

        myctx = ctx;

        System.out.println("客户端与服务端通道-开启:" + ctx.channel().localAddress() + "channelActive");

//        String sendInfo = "Hello 这里是third客户端  你好啊!";
//        System.out.println("客户端准备发送的数据包:" + sendInfo);
//        ctx.writeAndFlush(Unpooled.copiedBuffer(sendInfo, CharsetUtil.UTF_8)); // 必须有flush

    }

    /**
     * channelInactive
     *
     * channel 通道 Inactive 不活跃的
     *
     * 当客户端主动断开服务端的链接后,这个通道就是不活跃的。也就是说客户端与服务端的关闭了通信通道并且不可以传输数据
     *
     */
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        System.out.println("客户端与服务端通道-关闭:" + ctx.channel().localAddress() + "channelInactive");
        System.out.println("--------------------client: channel log end--------------------");
    }

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, ByteBuf msg) throws Exception {
        System.out.println("读取客户端通道信息..");
        ByteBuf buf = msg.readBytes(msg.readableBytes());
        System.out.println(
                "客户端接收到的服务端信息:" + ByteBufUtil.hexDump(buf) + "; 数据包为:" + buf.toString(Charset.forName("utf-8")));
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        ctx.close();
        System.out.println("异常退出:" + cause.getMessage());
    }
}

ThirdServer.java

package com.me.socket.server;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
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.bytes.ByteArrayEncoder;
import io.netty.handler.codec.string.StringEncoder;

import java.nio.charset.Charset;

public class ThirdServer {
    private final int port;

    public ThirdServer(int port) {
        this.port = port;
    }

    public void start() throws Exception {
        EventLoopGroup bossGroup = new NioEventLoopGroup();

        EventLoopGroup group = new NioEventLoopGroup();
        try {
            ServerBootstrap sb = new ServerBootstrap();
            sb.option(ChannelOption.SO_BACKLOG, 1024);
            sb.group(group, bossGroup) // 绑定线程池
                    .channel(NioServerSocketChannel.class) // 指定使用的channel
                    .localAddress(this.port)// 绑定监听端口
                    .childHandler(new ChannelInitializer<SocketChannel>() { // 绑定客户端连接时候触发操作

                        @Override
                        protected void initChannel(SocketChannel ch) throws Exception {
                            System.out.println("--------------------server: channel log begin--------------------");
                            System.out.println("报告");
                            System.out.println("信息:有一客户端链接到本服务端");
//                            System.out.println("IP:" + ch.localAddress().getHostName());
                            System.out.println("IP:" + ch.remoteAddress().getHostName());
//                            System.out.println("Port:" + ch.localAddress().getPort());
                            System.out.println("Port:" + ch.remoteAddress().getPort());
                            System.out.println("报告完毕");

                            ch.pipeline().addLast(new StringEncoder(Charset.forName("GBK")));
                            ch.pipeline().addLast(new ThirdServerHandler()); // 客户端触发操作
                            ch.pipeline().addLast(new ByteArrayEncoder());
                        }
                    });
            ChannelFuture cf = sb.bind().sync(); // 服务器异步创建绑定
            System.out.println(ThirdServer.class + " 启动正在监听: " + cf.channel().localAddress());
            cf.channel().closeFuture().sync(); // 关闭服务器通道
        } finally {
            group.shutdownGracefully().sync(); // 释放线程池资源
            bossGroup.shutdownGracefully().sync();
        }
    }

    public static void main(String[] args) throws Exception {

        new ThirdServer(8883).start(); // 启动
    }
}

ThirdServerHandler.java

package com.me.socket.server;

import com.me.socket.client.ThirdClient;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;

import java.io.UnsupportedEncodingException;

public class ThirdServerHandler extends ChannelInboundHandlerAdapter {

    private String rev;

    /**
     * channelAction
     *
     * channel 通道 action 活跃的
     *
     * 当客户端主动链接服务端的链接后,这个通道就是活跃的了。也就是客户端与服务端建立了通信通道并且可以传输数据
     *
     */
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        System.out.println(ctx.channel().localAddress().toString() + " 通道已激活!");
    }

    /**
     * channelInactive
     *
     * channel 通道 Inactive 不活跃的
     *
     * 当客户端主动断开服务端的链接后,这个通道就是不活跃的。也就是说客户端与服务端的关闭了通信通道并且不可以传输数据
     *
     */
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        System.out.println(ctx.channel().localAddress().toString() + " 通道不活跃!");
        // 关闭流

        System.out.println("--------------------server: channel log end--------------------");
    }

    /**
     * TODO  此处用来处理收到的数据中含有中文的时  出现乱码的问题
     * @param buf
     * @return
     */
    private String getMessage(ByteBuf buf) {
        byte[] con = new byte[buf.readableBytes()];
        buf.readBytes(con);
        try {
            return new String(con, "UTF-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
            return null;
        }
    }

    /**
     * 功能:读取second-server发送过来的信息
     */
    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        // 第一种:接收字符串时的处理
        ByteBuf buf = (ByteBuf) msg;
//        String rev = getMessage(buf);
        rev = getMessage(buf);
        System.out.println("third-server收到second-server发送的数据:" + rev);

    }

    /**
     * 功能:读取完毕客户端发送过来的数据之后的操作
     */
    @Override
    public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
        System.out.println("服务端接收数据完毕..");
        // 第一种方法:写一个空的buf,并刷新写出区域。完成后关闭sock channel连接。
        ctx.writeAndFlush(Unpooled.EMPTY_BUFFER).addListener(ChannelFutureListener.CLOSE);

        // transfer data to 8884: result-server
//        ThirdClient thirdClient = new ThirdClient("127.0.0.1", 8884);
        // data to send after third operations
//        thirdClient.connect(rev+" | third msg");

        // ctx.flush();
        // ctx.flush(); //
        // 第二种方法:在client端关闭channel连接,这样的话,会触发两次channelReadComplete方法。
        // ctx.flush().close().sync(); // 第三种:改成这种写法也可以,但是这中写法,没有第一种方法的好。
    }

    /**
     * 功能:服务端发生异常的操作
     */
    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        ctx.close();
        System.out.println("异常信息:\r\n" + cause.getMessage());
    }
}


Demo操作流程

1. 启动ThirdServer
2. 启动SecondServer
3. 启动FirstClient

输出结果

FirstClient

--------------------client: channel log begin--------------------
正在连接中...
服务端连接成功...
客户端与服务端通道-开启:/127.0.0.1:54088channelActive
连接已关闭..
客户端与服务端通道-关闭:/127.0.0.1:54088channelInactive
--------------------client: channel log end--------------------
=========================

SecondServer

class com.me.socket.server.SecondServer 启动正在监听: /0:0:0:0:0:0:0:0:8882
--------------------server: channel log begin--------------------
报告
信息:有一客户端链接到本服务端
IP:127.0.0.1
Port:54088
报告完毕
/127.0.0.1:8882 通道已激活!
second-server收到first-server发送的数据:{name='xyz', id=999, list=[111, 222, 333]}
服务端接收数据完毕..
--------------------client: channel log begin--------------------
正在连接中...
客户端与服务端通道-开启:/127.0.0.1:54113channelActive
服务端连接成功...
连接已关闭..
客户端与服务端通道-关闭:/127.0.0.1:54113channelInactive
--------------------client: channel log end--------------------
/127.0.0.1:8882 通道不活跃!
--------------------server: channel log end--------------------

ThirdServer

class com.me.socket.server.ThirdServer 启动正在监听: /0:0:0:0:0:0:0:0:8883
--------------------server: channel log begin--------------------
报告
信息:有一客户端链接到本服务端
IP:127.0.0.1
Port:54113
报告完毕
/127.0.0.1:8883 通道已激活!
third-server收到second-server发送的数据:{name='当前位置second', id=888, list=[111, 222, 333, 444]} | second msg
服务端接收数据完毕..
/127.0.0.1:8883 通道不活跃!
--------------------server: channel log end--------------------

源码地址

Netty socket demo 源码地址

GitHub 地址

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值