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

13 篇文章 0 订阅

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";
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值