**
SWOOLE简单 单人聊天室(php)
**
服务器可使用宝塔…自配环境也可以.
端口号可以自定义. “9200”,
在服务器找到此文件,php 文件名,运行即可.
php
<?php
//创建WebSocket Server对象,监听0.0.0.0:9502端口
$ws = new Swoole\WebSocket\Server('0.0.0.0', 9200);
//监听WebSocket连接打开事件
$ws->on('Open', function ($ws, $request) {
$ws->push($request->fd, "hello, welcome\n");
});
//监听WebSocket消息事件
$ws->on('Message', function ($ws, $frame) {
$data = $frame->data;
$ret['data'] = $data;
foreach ($ws->connections as $client){
if ($frame->fd == $client ){
$ret['style'] = 'bubble me';
}else{
$ret['style'] = 'bubble you';
}
@$ws->push($client,json_encode($ret,256));
}
});
//监听WebSocket连接关闭事件
$ws->on('Close', function ($ws, $fd) {
echo "client-{$fd} is closed\n";
});
$ws->start();
?>
html
<!DOCTYPE html>
<html lang="en" >
<head>
<meta charset="UTF-8">
<title>在线聊天室</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="css/reset.min.css">
<link rel="stylesheet" href="css/style.css">
</head>
<body>
<div class="wrapper">
<div class="container">
<div class="left">
<div class="top"> 在线人员 </div>
<ul class="people">
<li class="person" data-chat="person1">
<img src="img/thomas.jpg" alt="" />
<span class="name">张三</span>
<span class="time">10:09</span>
</li>
<li class="person" data-chat="person2">
<img src="img/dog.png" alt="" />
<span class="name">李四</span>
<span class="time">10:44</span>
</li>
<li class="person" data-chat="person3">
<img src="img/louis-ck.jpeg" alt="" />
<span class="name">王五</span>
<span class="time">10:50</span>
</li>
</ul>
</div>
<div class="right">
<div class="top"><span><span class="name">聊天室</span></span></div>
<div class="chat" data-chat="person2">
<template v-for='item in msglist'>
<div :class="item.style">
{{ item.data }}
</div>
</template>
</div>
<div class="write">
<input type="text" v-model="msg" placeholder="输入内容" @keydown.enter="send" />
<a @click.prevent="send" class="write-link send"></a>
</div>
</div>
</div>
</div>
<script src="js/index.js"></script>
</body>
</html>
<script src="https://cdn.jsdelivr.net/npm/vue"></script>
<script>
const ws = new WebSocket('ws://0.0.0.0:0000');
ws.onopen = () =>{
console.log("连接建立")
}
ws.onmessage = ({data}) =>{
let json = JSON.parse(data)
vm.msglist.push(json)
}
const vm = new Vue({
el:".wrapper",
data:{
msg: '',
msglist: []
},
methods:{
send() {
ws.send(this.msg);
this.msg = ''
}
}
})
</script>
这的"const ws = new WebSocket(‘ws://0.0.0.0:0000’);"需自己等于端口号与自己服务器的端口号相同.
查看详情:
文档:单人聊天(1).note (有道云)
链接:http://note.youdao.com/noteshare?id=ec4673a353d7fbb573c24a5c04181d55&sub=1DE34DFC900240EC93BD6540CD4EF025