websocket.html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> </body> <script> var wsServer = 'ws://xxxxxx:9501'; var websocket = new WebSocket(wsServer); websocket.onopen = function (evt) { console.log("Connected to WebSocket server."); var data = { 'code':1, // 我们假设code为1时,是绑定登录请求 'user_id':1111 }; // 前端发送json前,必须先转义成字符串 data = JSON.stringify(data); console.log(data); websocket.send(data); //websocket.send("Hello WebSockets!"); }; websocket.onclose = function (evt) { console.log("Disconnected"); }; websocket.onmessage = function (evt) { console.log('Retrieved data from server: ' + evt.data); }; websocket.onerror = function (evt, e) { console.log('Error occured: ' + evt.data); }; </script> </html>
websocket.php
<?php $server = new SwooleWebSocketServer("0.0.0.0", 9501); $set = array( 'heartbeat_idle_time' => 600, // 表示一个连接如果600秒内未向服务器发送任何数据,此连接将被强制关闭 'heartbeat_check_interval' => 60, // 表示每60秒遍历一次 ); $server->set($set); $server->on('open', function (SwooleWebSocketServer $server, $request) { echo "server: handshake success with fd{$request->fd} "; }); $server->on('message', function (SwooleWebSocketServer $server, $frame) { echo "receive from {$frame->fd}:{$frame->data},opcode:{$frame->opcode},fin:{$frame->finish} "; $server->push($frame->fd, "this is server"); }); $server->on('close', function ($ser, $fd) { echo "client {$fd} closed "; }); $server->start();
<?php $server = new SwooleServer('127.0.0.1', 9501); $set = array( 'heartbeat_idle_time' => 600, // 表示一个连接如果600秒内未向服务器发送任何数据,此连接将被强制关闭 'heartbeat_check_interval' => 60, // 表示每60秒遍历一次 ); $server->set($set); //监听连接进入事件 $server->on('Connect', function ($server, $fd) { echo "Client: Connect. "; }); //监听数据接收事件 $server->on('Receive', function ($server, $fd, $from_id, $data) { $user = json_decode($data, true); echo $user['userId'] . '登陆了'; $server->send($fd, "Server: " . $data); }); //监听连接关闭事件 $server->on('Close', function ($server, $fd) { echo $fd . '关闭了'; echo "Client: Close. "; }); //启动服务器 $server->start();