ws_server.php
<?php
//创建websocket服务器对象,监听0.0.0.0:9502端口
$ws = new swoole_websocket_server("0.0.0.0", 9502);
//监听WebSocket连接打开事件
$ws->on('open', function ($ws, $request) {
var_dump($request->fd, $request->get, $request->server);
$ws->push($request->fd, $request->fd." hello, welcome\n");
});
//监听WebSocket消息事件
$ws->on('message', function ($ws, $frame) {
var_dump($ws->connections);
echo "Message: {$frame->data}\n";
echo "receive from {$frame->fd}:{$frame->data},opcode:{$frame->opcode},fin:{$frame->finish}\n";
foreach($ws->connections as $fd) {
echo 'test'.$fd;
if($frame->fd == $fd){
$ws->push($fd, '<p class="myInfo">我对大家说:'.$frame->data.'</p>');
}else{
$ws->push($fd, '<p class="otherInfo">'.$frame->fd.'对大家说:'.$frame->data.'</p>');
}
}
// $ws->push($frame->fd, "server: {$frame->data}");
});
//监听WebSocket连接关闭事件
$ws->on('close', function ($ws, $fd) {
echo "client-{$fd} is closed\n";
});
$ws->start();
index.html
<html>
<script type="text/javascript" src="jquery-1.8.3.min.js"></script>
<head>
<style>
#chatRecord{
width:600px;
height:500px;
border:1px solid #EDEDED;
overflow-x:hidden;
}
.otherInfo{
margin-left:8px;
float:left;
clear:both;
padding:6px;
background-color:#FFFFFF;
border:1px solid #EDEDED;
}
.myInfo{
margin-right:8px;
float:right;
clear:both;
padding:6px;
background-color:#9EEA6A;
border:1px solid #9EEA6A;
}
#chatInfo{
width:600px;
height:150px;
border:1px solid #EDEDED;
}
#sendInfo{
display:block;
float:right;
}
#sendArea{
width:600px;
}
#chatInfo{
display:block;
}
</style>
</head>
<body>
<div>
<div id="chatRecord"></div>
<div id="sendArea">
<textarea name="chatInfo" id="chatInfo"></textarea>
<input type="button" id="sendInfo" value="send" onclick="send()"/>
</div>
</div>
</body>
<script>
$(function(){
enterExe('body', 'sendInfo');
})
var wsServer = 'ws://192.168.164.100:9502';
var websocket = new WebSocket(wsServer);
websocket.onopen = function (evt) {
console.log("Connected to WebSocket server.");
};
websocket.onclose = function (evt) {
console.log("Disconnected");
};
websocket.onmessage = function (evt) {
console.log(evt);
showChatInfo(evt.data);
console.log('Retrieved data from server: ' + evt.data);
};
websocket.onerror = function (evt, e) {
console.log('Error occured: ' + evt.data);
};
function send(){
var info = $('#chatInfo').val();
$('#chatInfo').val('');
websocket.send(info);
}
function showChatInfo(msg){
$('#chatRecord').append(msg);
var scrollHeight = $("#chatRecord").prop("scrollHeight");
$("#chatRecord").animate({scrollTop:scrollHeight}, 400);
}
function enterExe(parentTag, tagId){
$(""+parentTag).unbind('keydown').keydown(function (event) {
if (event.keyCode == "13") {
$('#'+tagId).click();
}
});
}
</script>
</html>
swoole扩展安装后,运行php ws_server.php
浏览器访问index.html
简易界面效果如下: