首页 > 编程语言 >PHP 之phpsocket.io简易聊天室

PHP 之phpsocket.io简易聊天室

时间:2023-12-30 13:55:20浏览次数:33  
标签:chat frameHead phpsocket fd io message PHP true out

一、安装

composer require workerman/phpsocket.io

二、服务端和客户端连接

<?php

require_once './vendor/autoload.php';

use Workerman\Worker;
use PHPSocketIO\SocketIO;

$io = new SocketIO(3120);

// 当有客户端连接时
$io->on('connection', function($socket)use($io){
    // 定义chat message事件回调函数
    $socket->on('chat message', function($data)use($io){
        // 触发所有客户端定义的chat message from server事件
        var_dump($data);
        $io->emit('chat message from server', $data);
    });

});

Worker::runAll();

三、客户端

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>聊天室</title>
</head>
<body>
<div id="msg_box">

</div>


<div id="input-box">
    <input type="text" id="msg_input"><button onclick="send()">发送</button>
</div>

<script src='https://lib.baomitu.com/socket.io/1.7.4/socket.io.min.js'></script>
<script>
    // 连接服务端
    var socket = io('http://127.0.0.1:3120');

    function send()
    {
        var msg = document.querySelector('#msg_input').value;
        socket.emit('chat message', msg);
        document.querySelector('#msg_input').value = '';
    }

    // 服务端通过emit('chat message from server', $msg)触发客户端的chat message from server事件
    socket.on('chat message from server', function(msg){
        var oDiv = document.createElement('div');
        oDiv.innerHTML = msg;
        document.querySelector('#msg_box').appendChild(oDiv);
    });

</script>
</body>
</html>

四、广播给客户端

<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2023/12/30 0030
 * Time: 13:21
 */

class SocketIO
{
    /**
     * 发送数据
     * @param null $host
     * @param null $port
     * @param string $action
     * @param null $data
     * @param string $address
     * @param string $transport
     * @return bool
     */
    public function send($host = null, $port = null, $action = "message", $data = null, $address = "/socket.io/?EIO=2", $transport = 'websocket')
    {
        $fd = fsockopen($host, $port, $errno, $errstr);
        if (!$fd) {
            return false;
        } //Can't connect tot server
        $key = $this->generateKey();
        $out = "GET $address&transport=$transport HTTP/1.1\r\n";
        $out .= "Host: http://$host:$port\r\n";
        $out .= "Upgrade: WebSocket\r\n";
        $out .= "Connection: Upgrade\r\n";
        $out .= "Sec-WebSocket-Key: $key\r\n";
        $out .= "Sec-WebSocket-Version: 13\r\n";
        $out .= "Origin: *\r\n\r\n";

        fwrite($fd, $out);
        // 101 switching protocols, see if echoes key
        $result = fread($fd, 10000);

        preg_match('#Sec-WebSocket-Accept:\s(.*)$#mU', $result, $matches);
        $keyAccept = trim($matches[1]);
        $expectedResonse = base64_encode(pack('H*', sha1($key . '258EAFA5-E914-47DA-95CA-C5AB0DC85B11')));
        $handshaked = ($keyAccept === $expectedResonse) ? true : false;
        if ($handshaked) {
            if ($action){
                fwrite($fd, $this->hybi10Encode('42["' . $action . '", "' . addslashes($data) . '"]'));
            }else{
                fwrite($fd, $this->hybi10Encode(addslashes($data)));
            }
            $content = '';
            while (!feof($fd)) {
                stream_set_timeout($fd, 1);
                $content .= fread($fd, 1024);
                $info = stream_get_meta_data($fd);
                if ($info['timed_out']) {
                    break;
                }
            }
            //fread($fd,1000000);
            fclose($fd);
            return true;
        } else {
            return false;
        }
    }

    private function generateKey($length = 16)
    {
        $c = 0;
        $tmp = '';
        while ($c++ * 16 < $length) {
            $tmp .= md5(mt_rand(), true);
        }
        return base64_encode(substr($tmp, 0, $length));
    }

    private function hybi10Encode($payload, $type = 'text', $masked = true)
    {
        $frameHead = array();
        $payloadLength = strlen($payload);
        switch ($type) {
            case 'text':
                $frameHead[0] = 129;
                break;
            case 'close':
                $frameHead[0] = 136;
                break;
            case 'ping':
                $frameHead[0] = 137;
                break;
            case 'pong':
                $frameHead[0] = 138;
                break;
        }
        if ($payloadLength > 65535) {
            $payloadLengthBin = str_split(sprintf('%064b', $payloadLength), 8);
            $frameHead[1] = ($masked === true) ? 255 : 127;
            for ($i = 0; $i < 8; $i++) {
                $frameHead[$i + 2] = bindec($payloadLengthBin[$i]);
            }
            if ($frameHead[2] > 127) {
                $this->close(1004);
                return false;
            }
        } elseif ($payloadLength > 125) {
            $payloadLengthBin = str_split(sprintf('%016b', $payloadLength), 8);
            $frameHead[1] = ($masked === true) ? 254 : 126;
            $frameHead[2] = bindec($payloadLengthBin[0]);
            $frameHead[3] = bindec($payloadLengthBin[1]);
        } else {
            $frameHead[1] = ($masked === true) ? $payloadLength + 128 : $payloadLength;
        }
        foreach (array_keys($frameHead) as $i) {
            $frameHead[$i] = chr($frameHead[$i]);
        }
        if ($masked === true) {
            $mask = array();
            for ($i = 0; $i < 4; $i++) {
                $mask[$i] = chr(rand(0, 255));
            }
            $frameHead = array_merge($frameHead, $mask);
        }
        $frame = implode('', $frameHead);
        for ($i = 0; $i < $payloadLength; $i++) {
            $frame .= ($masked === true) ? $payload[$i] ^ $mask[$i % 4] : $payload[$i];
        }
        return $frame;
    }
}

$socket = new SocketIO();
//发送消息到服务端,广播消息给所有客户端
$res = $socket->send('127.0.0.1', 3120, 'chat message', 'this is a test');
var_dump($res);

五、文档

https://www.workerman.net/phpsocket_io

标签:chat,frameHead,phpsocket,fd,io,message,PHP,true,out
From: https://www.cnblogs.com/yang-2018/p/17936298.html

相关文章

  • A Long read hybrid error correction algorithm based on segmented pHMM
    ALongreadhybriderrorcorrectionalgorithmbasedonsegmentedpHMM  2023/12/1511:06:36The"LongreadhybriderrorcorrectionalgorithmbasedonsegmentedpHMM"referstoaspecificapproachforerrorcorrectioninlong-readse......
  • 2023 Music Exhibition
    ......
  • check the manual that corresponds to your MySQL server version for the right syn
    form:{repairstatus:0,name:'',//负责人maintenancetime:newDate().toISOString().split('T')[0],//保修时间equipmentid:'',equipment:'',describe:'',finfishtime:'',repairname:'�......
  • Visio——Mac上可用的项目管理画图工具“Draw.io”
    背景:亮哥画的座位图、安老师夏雪画的流程图、邵工进行的项目进度管理,都是用的Visio,看来想要画个非专业建模图,这是一个很好地工具。  Draw.io因为Visio是微软的软件,只支持Windows系统。所以,要想在Mac上使用Visio,就可以考虑替代品。我自己找了几个,发现Draw.io,可以直接在线使......
  • 去除X-FRAME-OPTIONS响应头的Chrome插件
    为了创建一个Chrome插件来移除document请求中的X-Frame-Options,你可以按照以下步骤进行操作:创建一个新的文件夹作为插件项目的根目录。在根目录下创建一个名为manifest.json的文件,并添加必要的清单信息,例如:{"manifest_version":2,"name":"RemoveX-Frame-Options......
  • 用python打开文件获取文件属性时,运行报错PermissionError: [Errno 13] Permission den
    一:概述在开发中我们经常会使用python程序去对物理主机平台上的文件进行操作,在这里说明一下,python中获取文件属性时,运行出现的错误。二:具体说明<1>获取文件属性的代码importos#创建一个临时目录temp_dir='temp'os.mkdir(temp_dir)#在临时目录中创建一个文件temp_file=o......
  • 下载文件报错:java.io.IOException: UT010029: Stream is closed
    在项目中使用EasyExcel导出excel然后压缩成压缩包下载,下载也是能正常下载就是会抛出这个错误虽然说这个错误不影响下载功能,搞不好就因为这个错误某天系统崩溃,那时候就不是这么好玩了,于是我在百度上疯狂查找有的说是流没有关,要在finally里面把流关了关了之后,满怀期待的重新运......
  • 【APIO2016】烟火表演
    先前的题目对slopetrick的认识还不深刻,这题可以看出一个完整的构建过程。题目描述给定一棵有根树,根为\(1\),边带权,修改边权的代价时修改值与原值差的绝对值,求让所有叶子到根距离相等的最小代价。\(1\leqn\leq3\times10^5,1\leqw\leq10^9\)。算法解析首先有朴......
  • 【五期李伟平】CCF-B(TFS'23)Consensus Reaching Process With Multiobjective Optimiza
    PengWu,FengenLi,JieZhao,etal.ConsensusReachingProcessWithMultiobjectiveOptimizationforLarge-ScaleGroupDecisionMakingWithCooperativeGame[J].IEEETransactionsonFuzzySystems2023:293-306.  本文针对大规模群体决策(LSGDM)中的共识达成......
  • dremio nessie数据源集成简单说明
    nessie是一个强大的支持类似git分之特性的apacheiceberg智能元数据存储,主要测试下基于nessiedremio元数据存储(catalog)集成参考架构环境准备docker-compose文件version:"3"services:minio:image:minio/minioports:-"90......