php代码
<?php
class WS
{
private $server = null;
public function __construct()
{
$this->server = new Swoole\WebSocket\Server('0.0.0.0', 9502);
$this->server->on('Open', [$this, 'open']);
$this->server->on('Message', [$this, 'message']);
$this->server->on('Close', [$this, 'close']);
$this->server->start();
}
public function open($ws, $request)
{
$ws->push($request->fd, "hello, welcome\n");
}
public function message($ws, $frame)
{
echo "Message: {$frame->data}\n";
foreach ($ws->connections as $fd) {
if ($fd == $frame->fd) {
$ws->push($fd, "我:{$frame->data}");
} else {
$ws->push($fd, "对方:{$frame->data}");
}
}
}
public function close($ws, $fd)
{
echo "client-{$fd} is closed\n";
}
}
new WS();
前端代码
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<input id="val" type="text">
<input onclick="fasong()" type="button" value="点击">
</body>
<script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.7.1/jquery.js"></script>
<script>
var ws = new WebSocket('ws://localhost:9502');
function open(){
console.log('open');
}
function message(e){
console.log("收到消息了:",e)
}
function close(){
console.log('关闭')
}
function error(){
console.log('error');
}
ws.onopen =open;
ws.onmessage=message;
ws.onclose=close;
ws.onerror=error;
function fasong(){
let val = $('#val').val();
console.log(val);
ws.send(val);
$('#val').val('');
}
</script>
</html>