Websocket.php
<?php
$ws_server = new swoole_websocket_server('此处是你的域名/ip',端口号);
//设置server运行时的参数
$ws_server->set(array(
'daemonize' => true, //是否作为守护进程
'log_file' => __DIR__ .'/logs/web_socket.log' //存放聊天记录日志
));
//监听WebSocket连接打开事件
$ws_server->on('open', function ($ws, $request) {
// $ws->push($request->fd, $request->fd.' : '."Hello\n");
});
//监听WebSocket消息事件
$ws_server->on('message', function ($ws, $frame) {
pushMessage($ws,$frame->data,$frame->fd);
});
//监听WebSocket连接关闭事件
$ws_server->on('close', function ($ws, $fd) {
echo date('Y-m-d H:i:s').' 游客ID-'.$fd.' 退出了聊天室'."\r\n";
});
$ws_server->start();
//消息推送
function pushMessage($ws,$data,$fd){
echo date('Y-m-d H:i:s').' 游客ID-'.$fd.':'.$data."\r\n";
foreach($ws->connections as $dd){
$ws->push($dd, $fd.' : '.$data);
}
}
websocket.html
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title>强强聊天室</title>
<script type="text/javascript" charset="utf-8" >
if(window.WebSocket){
var url = "ws://域名或ip:端口"
// 创建WebSocket 对象
var webSocket = new WebSocket(url);
console.log(webSocket.readyState);
if (webSocket.readyState===0) {
console.log("正在连接"+url+"")
}else if(webSocket.readyState ===1){
console.log("连接成功"+url+"")
}else if(webSocket.readyState ===1){
console.log("正在关闭"+url+"")
}else if(webSocket.readyState ===1){
console.log("表示连接已经关闭,或者打开连接失败"+url+"")
}
//连接成功时,触发事件
webSocket.onopen = function (event) {
};
webSocket.onmessage = function (event) {
var content = document.getElementById('content');
content.innerHTML = content.innerHTML.concat('<p >游客id-'+event.data+'</p>');
content.scrollTop = content.scrollHeight;
document.getElementById("message").value="";
}
var sendMessage = function(){
var data = document.getElementById('message').value;
console.log("连接状态"+webSocket.readyState);
if (webSocket.readyState===1 && data != '') {
webSocket.send(data);
}
}
}else{
console.log("浏览器不支持WebSocket");
}
var submitMi = function (keyNum) {
if (keyNum == "13") {
//回车执行查询
if (document.getElementById('message').value != '') {
sendMessage();
}
}
}
</script>
<style >
p {
margin-left:20px;
height:8px;
line-height:20px;
}
#title {
text-align: center;
margin-bottom: 10px;
}
#room {
width: 600px;
border: 1px solid #ccc;
margin:0 auto;
}
#content {
overflow-y:auto;
height:300px;
border: 1px solid #ccc;
}
#talk {
height:40px;
margin-top:10px
}
#message {
margin-left:10px;
height:25px;
width:450px;
}
#sendButton {
margin-left:20px;
height:30;
width: 70px;
}
</style>
</head>
<body>
<div id="title" >基于php swoole扩展写的超简单聊天室</div>
<div id="room" >
<div id="content" ></div>
<div id="talk" >
<input type="text" id="message" placeholder="说点什么吧..." onkeypress="submitMi(event.keyCode)">
<button id = "sendButton" onclick="sendMessage()" >发送</button>
</div>
</div>
</body>
</html>
|