js
var wsServer = 'ws://127.0.0.1:9502';
//调用websocket对象建立连接:
//参数:ws/wss(加密)://ip:port (字符串)
var websocket = new WebSocket(wsServer);
//onopen监听连接打开
websocket.onopen = function (evt) {
console.log('this is a test')
//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.
*/
};
//监听连接关闭
websocket.onclose = function (evt) {
console.log("Disconnected");
};
//onmessage 监听服务器数据推送
websocket.onmessage = function (evt) {
console.log(evt);
// console.log('Retrieved data from server: ' + evt.data);
};
//监听连接错误信息
websocket.onerror = function (evt, e) {
console.log('Error occured: ' + evt.data);
};
php
$serv = new Swoole\Websocket\Server("127.0.0.1", 9502);
$serv->on('Open', function($server, $req) {
echo "connection open: ".$req->fd;
});
$serv->on('Message', function($server, $frame) {
echo "message: ".$frame->data;
$server->push($frame->fd, json_encode(["hello", "world"]));
});
$serv->on('Close', function($server, $fd) {
echo "connection close: ".$fd;
});
$serv->start();