Tcp客户端与服务端的搭建

1. 使用Netty框架进行通信

1.1 客户端代码

maven引用的依赖

       <dependency>
            <groupId>io.netty</groupId>
            <artifactId>netty-all</artifactId>
            <version>5.0.0.Alpha2</version>
        </dependency>

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();
        }
    }


}

客户端代码

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");
    }
}

服务端代码

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();
        }
    }


}

服务端代码

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)");
    }
}
  • 2
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
GatewayWorker 是一款基于PHP语言开发的高性能的TCP长连接框架,可以通过它来实现高并发的网络应用。而ThinkPHP是一款流行的PHP开发框架,提供了丰富的功能,包括MVC架构、ORM、模板引擎等等。 下面介绍如何使用ThinkPHP搭建GatewayWorker TCP客户端服务端。 ### 环境准备 - PHP 5.3以上版本(推荐PHP7) - GatewayWorker 3.0以上版本 - ThinkPHP 5.0以上版本 ### 客户端实现 在ThinkPHP的控制器中,我们可以使用GatewayClient类来实现对GatewayWorker服务端的连接和通信。以下是一个简单的示例: ```php use GatewayClient\Gateway; class IndexController extends \think\Controller { public function index() { Gateway::$registerAddress = '127.0.0.1:1238'; $client_id = Gateway::getClientIdByUid(1); Gateway::sendToClient($client_id, 'hello world'); } } ``` 在上面的代码中,我们首先设置了GatewayWorker服务端的注册地址,然后通过getClientIdByUid方法来获取客户端的连接ID,最后通过sendToClient方法向客户端发送消息。 ### 服务端实现 在ThinkPHP的控制器中,我们可以使用GatewayWorker的Gateway类来实现TCP服务端搭建和消息处理。以下是一个简单的示例: ```php use GatewayWorker\Gateway; class Test extends \think\Controller { public function index() { $gateway = new Gateway("websocket://0.0.0.0:7272"); $gateway->name = 'MyWebsocketGateway'; $gateway->count = 4; $gateway->onConnect = function($connection){ echo "new client connected\n"; }; $gateway->onMessage = function($connection, $data){ $connection->send('hello ' . $data); }; $gateway->onClose = function($connection){ echo "client closed\n"; }; $gateway->start(); } } ``` 在上面的代码中,我们首先创建了一个Gateway实例,并设置了监听地址和端口、名称、进程数等参数。然后我们定义了三个回调函数:onConnect、onMessage和onClose,分别处理客户端连接、消息接收和连接关闭的事件。最后我们调用start方法启动服务端。 ### 总结 本文介绍了如何使用ThinkPHP搭建GatewayWorker TCP客户端服务端。通过这种方式,我们可以很方便地实现高并发的网络应用。当然,GatewayWorker还提供了很多其他的功能,例如支持WebSocket协议、支持分布式部署等等。如果您想深入了解GatewayWorker的使用,可以参考官方文档。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

不一样的老墨

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值