Tcp客户端与服务端的搭建

1. 使用Netty框架进行通信

1.1 客户端代码

maven引用的依赖

pom 复制代码
       <dependency>
            <groupId>io.netty</groupId>
            <artifactId>netty-all</artifactId>
            <version>5.0.0.Alpha2</version>
        </dependency>
java 复制代码
package com.client;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.ChannelFuture;
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.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 java.net.InetSocketAddress;

public class NettyClient {

    public static void main(String[] args) throws Exception {
        EventLoopGroup group = new NioEventLoopGroup();
        try {
            Bootstrap b = new Bootstrap();
            b.group(group)
                    .channel(NioSocketChannel.class)
                    .handler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        protected void initChannel(SocketChannel ch) throws Exception {
                            ChannelPipeline p = ch.pipeline();
                            // 解码器:读取4个字节作为长度字段,调整偏移量为0
                   //        p.addLast(new LengthFieldBasedFrameDecoder(Integer.MAX_VALUE, 0, 400, 0, 0));
//                            // 编码器:将数据长度字段写入前4个字节
               //             p.addLast(new LengthFieldPrepender(4));
                           // 添加字符串编解码器
                            p.addLast(new StringDecoder(CharsetUtil.UTF_8));
                            p.addLast(new StringEncoder(CharsetUtil.UTF_8));
                            // 添加客户端处理器
                            p.addLast(new ClientHandler());
                        }
                    });

            ChannelFuture f = b.connect(new InetSocketAddress("localhost", 8082)).sync();
            f.channel().writeAndFlush("12").sync();

            f.channel().closeFuture().sync();
        } finally {
            group.shutdownGracefully();
        }
    }


}

客户端代码

java 复制代码
package com.client;

import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;

public class ClientHandler extends SimpleChannelInboundHandler<String> {


    @Override
    protected void messageReceived(ChannelHandlerContext channelHandlerContext, String s) throws Exception {
        System.out.println("Server received: " + s);

        // 向客户端回传消息
        System.out.println("服务端内容:`"+s);
        channelHandlerContext.writeAndFlush( "1");
    }
}

服务端代码

java 复制代码
package com.service;

import io.netty.bootstrap.ServerBootstrap;
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.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;

public class NettyServer {

    public static void main(String[] args) throws Exception {
        EventLoopGroup bossGroup = new NioEventLoopGroup(1);
        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 ch) throws Exception {
                  //          ch.pipeline().addLast(new LengthFieldBasedFrameDecoder(Integer.MAX_VALUE, 0, 400, 0, 0));
                           ch.pipeline().addLast(new StringDecoder());
                 //           ch.pipeline().addLast(new LengthFieldPrepender(4));
                           ch.pipeline().addLast(new StringEncoder());
                            ch.pipeline().addLast(new ServerHandler());



                        }
                    });

            ChannelFuture f = b.bind(8082).sync();
            f.channel().closeFuture().sync();
        } finally {
            bossGroup.shutdownGracefully();
            workerGroup.shutdownGracefully();
        }
    }


}

服务端代码

c 复制代码
package com.service;

import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;

public class ServerHandler extends SimpleChannelInboundHandler<String> {

    @Override
    protected void messageReceived(ChannelHandlerContext channelHandlerContext, String s) throws Exception {
        // 打印接收到的消息
        System.out.println("服务端接收: " + s);

        // 向客户端回传消息
        channelHandlerContext.writeAndFlush(s + " (from server)");
    }
}
相关推荐
小冷爱学习!26 分钟前
华为动态路由-OSPF-完全末梢区域
服务器·网络·华为
技术小齐1 小时前
网络运维学习笔记 016网工初级(HCIA-Datacom与CCNA-EI)PPP点对点协议和PPPoE以太网上的点对点协议(此处只讲华为)
运维·网络·学习
shimly1234563 小时前
tcpdump 用法示例
网络·测试工具·tcpdump
xmweisi4 小时前
【华为】报文统计的技术NetStream
运维·服务器·网络·华为认证
VVVVWeiYee5 小时前
BGP配置华为——路径优选验证
运维·网络·华为·信息与通信
yourkin6665 小时前
TCP...
服务器·网络·tcp/ip
哑巴语天雨7 小时前
前端面试-网络协议篇
websocket·网络协议·http·面试·https
ktkiko118 小时前
Websocket——心跳检测
网络·websocket·网络协议
GGGGGGGGGGGGGG.9 小时前
hapxory-ACL基础介绍及案例
运维·服务器·网络
小梁不秃捏10 小时前
HTTP 常见状态码技术解析(应用层)
网络·网络协议·计算机网络·http