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)");
    }
}
相关推荐
陈大爷(有低保)22 分钟前
UDP Socket聊天室(Java)
java·网络协议·udp
爱吃涮毛肚的肥肥(暂时吃不了版)27 分钟前
计算机网络34——Windows内存管理
网络·计算机网络·udp
码哝小鱼1 小时前
firewalld封禁IP或IP段
linux·网络
sec0nd_2 小时前
1网络安全的基本概念
网络·安全·web安全
青柠视频云2 小时前
青柠视频云——视频丢包(卡顿、花屏、绿屏)排查
服务器·网络·音视频
网安CILLE3 小时前
2024年某大厂HW蓝队面试题分享
网络·安全·web安全
沐风ya3 小时前
Reactor介绍,如何从简易版本的epoll修改成Reactor模型(demo版本代码+详细介绍)
网络
SUGERBOOM3 小时前
【网络安全】网络基础第一阶段——第一节:网络协议基础---- OSI与TCP/IP协议
网络·网络协议·web安全
petaexpress3 小时前
常用的k8s容器网络模式有哪些?
网络·容器·kubernetes
m0_609000425 小时前
向日葵好用吗?4款稳定的远程控制软件推荐。
运维·服务器·网络·人工智能·远程工作