PHP+SOCKET 服务端多进程处理多客户端请求 demo

服务端


$socket = socket_create(AF_INET,SOCK_STREAM,SOL_TCP);
socket_bind($socket,0,95012) or die( 'server bind fail:' . socket_strerror(socket_last_error()));
socket_listen($socket,5);

$child = 0; //初始化子进程数
while(true){
    $client = socket_accept($socket);

    $pid = pcntl_fork();
    if ($pid == -1) {
        die('could not fork');
    } else if ($pid) {
        socket_close($client);
        $child++;
        if($child >= 3){ //假设最大进程数为3
            pcntl_wait($status); //等待上一个进程结束
            $child--;
        }
    } else {
        while (true) {
            $buf = socket_read($client, 1024);
            echo $buf.PHP_EOL;
            if ($buf === FALSE || strcmp($buf, '') == 0) {
                $code = socket_last_error($client);
                socket_clear_error($client);
                if ($code == SOCKET_EAGAIN) {
                    // Nothing to read from non-blocking socket, try again later...
                    echo '无法从非阻塞套接字读取,请稍后再试..。';
                } else {
                    // Connection most likely closed, especially if $code is '0'
                    echo '连接很可能已关闭,特别是当 $code 为“0”时';
                    socket_close($client);
                    exit;//关闭子进程
                }

            }else {
                if (preg_match('/sleep/i', $buf)) {
                    sleep(10);
                    $html = 'HTTP/1.1 200 OK' . PHP_EOL
                        . 'Content-Type: text/html;charset=utf-8' . PHP_EOL . PHP_EOL;
                    socket_write($client, $html);
                    socket_write($client, "this is server,休克了10秒,模拟很繁忙的样子");
                } else {
                    socket_write($client, "this is server");
                }
            }
        }

    }
}

socket_close($socket);

客户端

$socket = socket_create(AF_INET,SOCK_STREAM,SOL_TCP);

socket_connect($socket, '127.0.0.1', 95012);

while (true){
    fwrite(STDOUT, '请输入消息:');
    $in = fgets(STDIN);
    //向服务端发送消息
    socket_write($socket,$in);
    //读取服务端消息
    $msg = socket_read($socket,1024);
    echo $msg.PHP_EOL;
}
socket_close($socket);

本文学习优化来源:https://blog.csdn.net/github_26672553/article/details/54582030

  • 8
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
要用 Netty 编写一个 Socket 服务端,实现和多个客户端通信,需要遵循以下步骤: 1. 创建 ServerBootstrap 实例并设置相关参数。 ```java EventLoopGroup bossGroup = new NioEventLoopGroup(); EventLoopGroup workerGroup = new NioEventLoopGroup(); try { ServerBootstrap b = new ServerBootstrap(); b.group(bossGroup, workerGroup) .channel(NioServerSocketChannel.class) .option(ChannelOption.SO_BACKLOG, 100) .handler(new LoggingHandler(LogLevel.INFO)) .childHandler(new ChannelInitializer<SocketChannel>() { @Override public void initChannel(SocketChannel ch) throws Exception { ChannelPipeline pipeline = ch.pipeline(); // 添加处理器 pipeline.addLast(new MyServerHandler()); } }); // 绑定端口,开始接收进来的连接 ChannelFuture f = b.bind(port).sync(); // 等待服务器 socket 关闭 。 // 在这个例子中,这不会发生,但你可以优雅地关闭你的服务器。 f.channel().closeFuture().sync(); } finally { // 优雅地关闭线程池 workerGroup.shutdownGracefully(); bossGroup.shutdownGracefully(); } ``` 2. 创建 ChannelInitializer,设置 ChannelPipeline。 ```java public class MyServerHandler extends ChannelInboundHandlerAdapter { @Override public void channelRead(ChannelHandlerContext ctx, Object msg) { // 处理消息 ByteBuf in = (ByteBuf) msg; System.out.println(in.toString(CharsetUtil.UTF_8)); // 响应客户端 ctx.write(in); } @Override public void channelReadComplete(ChannelHandlerContext ctx) { // 刷新缓冲区 ctx.flush(); } @Override public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) { // 异常处理 cause.printStackTrace(); ctx.close(); } } ``` 3. 在 ChannelInitializer 中添加自定义的处理器,例如 MyServerHandler。 ```java public class MyServerHandler extends ChannelInboundHandlerAdapter { @Override public void channelRead(ChannelHandlerContext ctx, Object msg) { // 处理消息 ByteBuf in = (ByteBuf) msg; System.out.println(in.toString(CharsetUtil.UTF_8)); // 响应客户端 ctx.write(in); } @Override public void channelReadComplete(ChannelHandlerContext ctx) { // 刷新缓冲区 ctx.flush(); } @Override public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) { // 异常处理 cause.printStackTrace(); ctx.close(); } } ``` 4. 编写客户端程序,连接到服务端。 ```java EventLoopGroup group = new NioEventLoopGroup(); try { Bootstrap b = new Bootstrap(); b.group(group) .channel(NioSocketChannel.class) .option(ChannelOption.TCP_NODELAY, true) .handler(new ChannelInitializer<SocketChannel>() { @Override public void initChannel(SocketChannel ch) throws Exception { ChannelPipeline pipeline = ch.pipeline(); // 添加处理器 pipeline.addLast(new MyClientHandler()); } }); // 连接服务器 ChannelFuture f = b.connect(host, port).sync(); // 发送消息 ByteBuf buf = Unpooled.copiedBuffer("Hello, world!", CharsetUtil.UTF_8); f.channel().writeAndFlush(buf); // 等待直到连接关闭 f.channel().closeFuture().sync(); } finally { // 优雅地关闭线程池 group.shutdownGracefully(); } ``` 这样,就可以使用 Netty 编写一个 Socket 服务端,实现和多个客户端通信。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值