YiluPHP
这家伙很懒,什么都没有留下...

经验 使用swoole建立websocket连接,聊天室发送信息,广播给所有用户

浏览数 197533
安装swoole的过程这里不讲述

服务器端创建一个php文件:socket.php
//创建websocket服务器对象,监听0.0.0.0:9502端口
$ws = new swoole_websocket_server("0.0.0.0", 9502);
//监听WebSocket连接打开事件
//0.0.0.0表示广播消息;
前端页面中使用的通信端口需要与这里开启的端口号9502一致
$ws->on('open', function ($ws, $request) {   //返回当次的连接ID //$ws->push($request->fd, "hello, welcome\n"); }); //监听WebSocket消息事件 $ws->on('message', function ($ws, $frame) { $msg = 'from'.$frame->fd.":{$frame->data}\n";
  //查看ws有哪些方法和变量,找出获取所有连接id的
  // $msg .= json_encode(get_class_methods($ws)).':vars:'.json_encode(get_class_vars($ws));
// $msg .= json_encode($ws->connection_list()).':getClientList:'.json_encode($ws->getClientList()); foreach($ws->getClientList() as $id){ $ws->push($id,$msg); } }); //监听WebSocket连接关闭事件 $ws->on('close', function ($ws, $fd) { $msg = "client-{$fd} is closed\n";
  echo $msg;
  foreach
($ws->getClientList() as $id){ $ws->push($
id,$msg); }
}); $ws->start();

客户端:socket.html

<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Titletitle>
head>
<body>
<div id="msg">div>
<input type="text" id="text">
<input type="submit" value="发送数据" onclick="song()">
body>
<script>
    var msg = document.getElementById("msg");
    var wsServer = 'ws://192.168.1.253:9502';
    //调用websocket对象建立连接:
    //参数:ws/wss(加密)://ip:port (字符串)
    var websocket = new WebSocket(wsServer);
    //onopen监听连接打开
    websocket.onopen = function (evt) {
        //websocket.readyState 属性:
        /*
        CONNECTING    0    The connection is not yet open.
        OPEN    1    The connection is open and ready to communicate.
        CLOSING    2    The connection is in the process of closing.
        CLOSED    3    The connection is closed or couldn't be opened.
        */
        msg.innerHTML = websocket.readyState;
    };

    function song(){
        var text = document.getElementById('text').value;
        document.getElementById('text').value = '';
        //向服务器发送数据
        websocket.send(text);
    }
      //监听连接关闭
//    websocket.onclose = function (evt) {
//        console.log("Disconnected");
//    };

    //onmessage 监听服务器数据推送
    websocket.onmessage = function (evt) {
        msg.innerHTML += evt.data +'
'
; // console.log('Retrieved data from server: ' + evt.data); }; //监听连接错误信息 // websocket.onerror = function (evt, e) { // console.log('Error occured: ' + evt.data); // };
script> html>
 

打开终端使用php cli 运行 socket.php 文件,这样就会启动swoole的websocket服务,并监听了服务器的9502端口。
查看端口使用情况,使用netstat命令
查看已经连接的服务端口(ESTABLISHED
  netstat -a
 
查看所有的服务端口(LISTEN,ESTABLISHED)
netstat -ap

查看8080端口,则可以结合grep命令:
netstat -ap | grep 8080

如查看8888端口,则在终端中输入:
lsof -i:8888

在浏览器里运行 socket.html 可以给服务器发消息了,若开启多个窗口,发消息后都可以看到最新消息。



我来说说