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)");
    }
}
相关推荐
密码小丑1 小时前
玄机-apache日志分析
网络·笔记·apache
学习2年半1 小时前
+++++背到厌倦。持续更新
网络·网络协议·rpc
秉承初心1 小时前
HTTP 压力测试工具autocannon(AI)
网络协议·测试工具·http
Lonwayne2 小时前
为什么ChatGPT选择SSE而非WebSocket?
websocket·网络协议·chatgpt·程序那些事
冰滚水2 小时前
网络建设与运维神州数码DCN sFlow网络流量信息协议
运维·网络·sflow·网络建设与运维·网络搭建·神州数码
Reggie_L2 小时前
网络初识 - Java
java·网络
茶茶只知道学习3 小时前
(2)网络学习之堡垒机
网络·学习
Brandon汐3 小时前
Linux文件传输:让数据飞起来!
linux·运维·网络
计算机鬼才~3 小时前
网络安全·第二天·ARP协议安全分析
网络·安全·web安全·arp
昊昊该干饭了6 小时前
玩转代理 IP :实战爬虫案例
运维·服务器·爬虫·网络协议·tcp/ip·网络爬虫