Swoole构建聊天室demo

websocket文档

原文出处

后端代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
//websocket.php
<?php
$server = new swoole_websocket_server("0.0.0.0", 9501);
$server->on('open', function (swoole_websocket_server $server, $request) {
file_put_contents( __DIR__ .'/log.txt' , $request->fd);
});
$server->on('message', function (swoole_websocket_server $server, $frame) {
global $client;
$data = $frame->data;
$m = file_get_contents( __DIR__ .'/log.txt');
for ($i=1 ; $i<= $m ; $i++) {
echo PHP_EOL . ' i is ' . $i . ' data is '.$data . ' m = ' . $m;
$server->push($i, $data );
}
});
$server->on('close', function ($ser, $fd) {
echo "client {$fd} closed\n";
});
$server->start();

前端代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
//index.html
<!DOCTYPE html>
<html>
<head>
<title></title>
<meta charset="UTF-8">
<script type="text/javascript">
var exampleSocket = new WebSocket("ws://0.0.0.0:9501");
exampleSocket.onopen = function (event) {
exampleSocket.send("亲爱的服务器!我连上你啦!");
};
exampleSocket.onmessage = function (event) {
console.log(event.data);
}
</script>
</head>
<body>
<input type="text" id="content">
<button onclick="exampleSocket.send( document.getElementById('content').value )">发送</button>
</body>
</html>

现在在本地命令行运行

1
php websocket.php

查看浏览器的console就可以测试了,swoole官方example中有个示例,这个demo就是为了抢先体验一下

这个博客有个赞赏功能,不试一下吗?