[李景山php]Swoole 编写 IM通信

来源:互联网 发布:北京东京 知乎 编辑:程序博客网 时间:2024/05/16 19:51

Swoole 编写 IM通信

服务器端口:

//创建websocket服务器对象,监听0.0.0.0:9502端口$ws = new swoole_websocket_server("0.0.0.0", 9502);//监听WebSocket连接打开事件$ws->on('open', function ($ws, $request) {$GLOBALS['fd'][$request->fd]['id'] = $request->fd;// 设置用户ID 安顺序递增$GLOBALS['fd'][$request->fd]['name'] = '匿名用户';// 设置用户名});//监听WebSocket消息事件$ws->on('message', function ($ws, $frame) {$msg = $GLOBALS['fd'][$frame->fd]['name'].":{$frame->data}\n";if(strstr($frame->data,'#name#')){// 用户设置昵称$GLOBALS['fd'][$frame->fd]['name'] = str_replace('#name#','',$frame->data);}else{// 普通发送用户信息foreach($GLOBALS['fd'] as $i){// 发送数据到客户端$ws->push($i['id'],$msg);}}});//监听WebSocket连接关闭事件$ws->on('close', function ($ws, $fd) {echo "客户端-{$fd} 断开连接\n";unset($GLOBALS['fd'][$fd]);// 清除 已经关闭的客户端});$ws->start();

客户端关键代码:

/** * Created by 27394 on 2017/4/24. */var msg = document.getElementById("msg");var wsServer = 'ws://192.168.50.151:9502';//调用websocket对象建立连接://参数:ws/wss(加密)://ip:port (字符串)var websocket = new WebSocket(wsServer);websocket.onopen = function (evt) {//onopen监听连接打开// 应该显示远程服务器连接成功//msg.innerHTML = websocket.readyState;//websocket.readyState 属性:/* CONNECTING 0The connection is not yet open. OPEN   1The connection is open and ready to communicate. CLOSING2The connection is in the process of closing. CLOSED 3The connection is closed or couldn't be opened. */};//onmessage 监听服务器数据推送websocket.onmessage = function (evt) {msg.innerHTML += evt.data +'<br>';//不断递增的数据console.log('从服务器获取到的数据: ' + evt.data);};//监听连接关闭websocket.onclose = function (evt) {console.log("服务器拒绝");};//监听连接错误信息websocket.onerror = function (evt, e) {console.log('错误: ' + evt.data);};//发送信息function send_msg(){var text = document.getElementById('text').value;// 获取数据document.getElementById('text').value = '';// 清空数据websocket.send(text);//向服务器发送数据}//发送昵称function send_name(){var text = document.getElementById('myname').value;// 获取数据websocket.send("#name#"+text);//向服务器发送数据var myTitle = document.getElementById("myTitle");myTitle.innerHTML = "IM "+text;alert("设置成功");var setName = document.getElementById("setName");setName.style.display = "none";var send_msg = document.getElementById("send_msg");send_msg.style.display = "block";}
0 0