Netty实现tcp通讯(telent发送消息)

版权声明:本文为博主原创文章,未经博主允许不得转载(需要转载联系QQ:787824374)!!! https://blog.csdn.net/qq_19107011/article/details/84645458

前言

参考Netty官网文档的例子,加了编码器、解码器。
实现了简单的tcp通讯。
代码很简单,最后我们会用Linux下的Telnet命令连接到服务端。并且给服务端发送消息。

代码

tcp服务端

package netty;

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.LineBasedFrameDecoder;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;
import sun.rmi.runtime.Log;

import java.util.logging.Logger;

public class DiscardServer {
    private static final Logger LOG = Logger.getLogger(DiscardServerHandler.class.getName());

    private int port;

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

    //启动server https://blog.csdn.net/KokJuis/article/details/72846388
    public void start() throws Exception {
        LOG.info("Server Start At port:"+port);
        EventLoopGroup bossGroup = new NioEventLoopGroup();
        EventLoopGroup workerGroup = new NioEventLoopGroup();
        try {
            ServerBootstrap b = new ServerBootstrap();
            b.group(bossGroup, workerGroup)
                    .channel(NioServerSocketChannel.class)
                    .childHandler(new ChannelInitializer<SocketChannel>() {

                        @Override
                        protected void initChannel(SocketChannel socketChannel) throws Exception {
                            socketChannel.pipeline().addLast(new LineBasedFrameDecoder(1024));
                            socketChannel.pipeline().addLast(new StringDecoder());
                            socketChannel.pipeline().addLast(new DiscardServerHandler());
                        }
                    })
                    .option(ChannelOption.SO_BACKLOG, 128)
                    .childOption(ChannelOption.SO_KEEPALIVE, true);
            ChannelFuture f = b.bind(port).sync();
            f.channel().closeFuture().sync();
        } finally {
            workerGroup.shutdownGracefully();
            bossGroup.shutdownGracefully();
        }


    }
}

消息处理类

package netty;

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

import java.util.logging.Logger;

public class DiscardServerHandler extends ChannelInboundHandlerAdapter {

    private static final Logger LOG = Logger.getLogger(DiscardServerHandler.class.getName());

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        LOG.info("客户端地址:"+ctx.channel().remoteAddress()+",消息:"+new String(msg.toString().getBytes()));
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        cause.printStackTrace();
        ctx.close();
    }
}

启动类

package netty;

public class Main {

    public static void main(String[] args) throws Exception {
        int port = 8080;
        if (args.length > 0) {
            port = Integer.parseInt(args[0]);
        }
        new DiscardServer(port).start();
    }
}

启动界面如下

十一月 30, 2018 10:57:49 上午 netty.DiscardServer start
信息: Server Start At port:8080

Linux下使用telnet发送消息

  1. 客户端:
[root@miv ~]# telnet 192.168.0.125 8080
Trying 192.168.0.125...
Connected to 192.168.0.125.
Escape character is '^]'.
这是来自Centos7发送的消息,hello Tcp
  1. 服务端:
十一月 30, 2018 10:57:49 上午 netty.DiscardServer start
信息: Server Start At port:8080
十一月 30, 2018 10:58:55 上午 netty.DiscardServerHandler channelRead
信息: 客户端地址:/192.168.0.115:34216,消息:这是来自Centos7发送的消息,hello Tcp
  1. 退出telnet(按Ctrl+],输入quit)
Trying 192.168.0.125...
Connected to 192.168.0.125.
Escape character is '^]'.
这是来自Centos7发送的消息,hello Tcp
^]
telnet> quit
Connection closed.

参考博客

猜你喜欢

转载自blog.csdn.net/qq_19107011/article/details/84645458