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)");
    }
}
相关推荐
孙克旭_12 分钟前
day051-ansible循环、判断与jinja2模板
linux·运维·服务器·网络·ansible
悟空胆好小1 小时前
分音塔科技(BABEL Technology) 的公司背景、股权构成、产品类型及技术能力的全方位解读
网络·人工智能·科技·嵌入式硬件
DoraBigHead2 小时前
《电磁波的浪漫,铜线上的灵魂》——计算机网络·物理层全解版
网络协议
ssswywywht3 小时前
OSPF实验
网络
FCM663 小时前
HCIA第一次实验报告:静态路由综合实验
网络·tcp/ip·信息与通信
apihz3 小时前
VM虚拟机全版本网盘+免费本地网络穿透端口映射实时同步动态家庭IP教程
android·服务器·开发语言·网络·数据库·网络协议·tcp/ip
dog2504 小时前
TCP 传输时 sk_buff 的 clone 和 unclone
网络·网络协议·tcp/ip
学习溢出4 小时前
【网络安全】理解安全事件的“三分法”流程:应对警报的第一道防线
网络·安全·web安全·网络安全·ids
智慧化智能化数字化方案5 小时前
华为IPD(集成产品开发)流程是其研发管理的核心体系
网络·华为ipd流程·ipd流程体系·ipd产品研发
kfepiza5 小时前
Linux的NetworkManager的nmcli配置网桥(bridge) 笔记250712
linux·运维·网络·笔记·tcp/ip·ip·tcp