通过swoole扩展,实现简单的匿名聊天室功能

  1. 项目组成
    1)、websocket.php
    构建websock服务,监听websock连接打开、关闭、消息接收事件,并实现消息推送
    2)、index.html
    展示聊天室聊天内容,提供聊天界面
    3)、log.txt
    记录聊天信息(出于简单考虑,我这里采用文件存储聊天记录)
  2. 功能效果
    通过swoole扩展,实现简单的匿名聊天室功能
  3. 具体代码
    websock.php:
$ws = new swoole_websocket_server("0.0.0.0", 9666);
$ws->user_c = [];   //给ws对象添加属性user_c,值为空数组;
//监听WebSocket连接打开事件
$ws->on('open', function ($ws, $request) {
	$ws->user_c[] = $request->fd;
	$msg = file_get_contents("log.txt");
	$msg = '';
	$file = fopen("/usr/local/apache/htdocs/swoole/log.txt","r");
	while(!feof($file)){
		$msg .= "<br>";
		$msg .= fgets($file);//fgets()函数从文件指针中读取一行
	}
	fclose($file);
	$ws->push( $request->fd,"$msg\n");
});



//监听WebSocket消息事件
$ws->on('message', function ($ws, $frame) {
	$arr = ['独孤九剑','童飘云','马钰','李秋水','齐御风','韩宝驹','无崖子','苏星河','丁春秋','阮星竹','刀白凤','秦红棉','王语嫣','木婉清','鸠摩智','张阿生','邓百川','公冶乾','包不同','风波恶','吴长风','白世镜','马大元','全冠清','上官云','令狐冲','东方不败','岳不群'];
	$index = $frame->fd >= 28 ? ($frame->fd%28):$frame->fd;
	$msg =  $arr[$index].":{$frame->data}";
	$handle = fopen("/usr/local/apache/htdocs/swoole/log.txt","a+");
	if(!empty($msg)){
		fwrite($handle,$msg."\r\n");
	}
	fclose($handle);
	echo $msg;
	foreach($ws->user_c as $v){
	      $ws->push($v,$msg);
	}
	// $ws->push($frame->fd, "server: {$frame->data}");
	// $ws->push($frame->fd, "server: {$frame->data}");
});

//监听WebSocket连接关闭事件
$ws->on('close', function ($ws, $fd) {
	echo "您已断开连接!";
	//删除已断开的客户端
	unset($ws->user_c[$fd-1]);
});

$ws->start();

index.html:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <style>
        #box{
            width:250px;
            overflow: hidden;
            margin:auto 20px;
        
        }
        #msg{
            border :1px solid #959595;
            margin:2px;
        }
    </style>
</head>
<body>
<div id="box">
    <div id="msg">
    </div>
    <div id="content">
        <input type="text" id="text" style="display:inline">
        <input type="submit" value="发送数据" onclick="song()" style="display:inline">
    </div>
</div>
</body>
<script>
    var msg = document.getElementById("msg");
    var wsServer = 'ws://127.0.0.1:9666';
    //调用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 +'<br>';
//        console.log('Retrieved data from server: ' + evt.data);
    };
//监听连接错误信息
//    websocket.onerror = function (evt, e) {
//        console.log('Error occured: ' + evt.data);
//    };

</script>
</html>

log.txt用于存储聊天记录