看代码之前呢,先来一张预览图
(因为这里填写图片会进行采集,但是采集失败,失败几次,放弃了,所以这里放图片链接)点击查看 预览图
PHP 部分
服务器呢,使用的是swoole 的websocket + table ,websocket 负责与前JS 进行通信,table 则负责记录用户信息,实现进程间的数据共享
server = new Server($host, $port);
$this->server->on('Open', [$this, 'onOpen']);
$this->server->on('Message', [$this, 'onMessage']);
$this->server->on('Close', [$this, 'onClose']);
// 内存表 实现进程间共享数据,也可以使用redis替代
$this->createTable();
}
private function createTable()
{
$this->table = new Table(1024);
$this->table->column('id', Table::TYPE_INT);
$this->table->column('name', Table::TYPE_STRING, 255);
$this->table->create();
}
public function run()
{
$this->server->start();
}
public function onOpen(Server $server, Request $request)
{
$user = ['id' => $request->fd, 'name' => ''];
$this->table->set($request->fd, $user);
}
public function onMessage(Server $server, Frame $frame)
{
$params = json_decode($frame->data, true);
// 接收到消息,根据消息类型进行不同的处理
switch ($params['action']) {
case self::ACTION_JOIN:
$this->join($frame->fd, $params['value']);
break;
case self::ACTION_SEND:
$this->send($frame->fd, $params['value']);
break;
}
}
public function onClose(Server $server, int $fd)
{
$user = $this->table->get($fd);
$this->table->del($fd);
echo "{$user['name']} 退出聊天室 \n";
$time = date('Y-m-d H:i:s');
// 将当前用户 '退出的消息' 推送给聊天室 剩余的其他用户
foreach ($this->table as $member) {
if ($member['id'] === $fd) {
continue;
}
$res = ['code' => 'someone_out', 'data' => [
'time' => $time, 'msg' => "{$user['name']} 退出聊天室",
'member_id' => $user['id']
]];
$this->server->push($member['id'], json_encode($res));
}
}
private function getMembers()
{
$members = [];
foreach ($this->table as $member) {
$members[] = $member;
}
return $members;
}
private function join(int $fd, string $name)
{
$user = $this->table->get($fd);
$user['name'] = $name;
// 将当前用户的信息 记录到 table 中
$this->table->set($fd, $user);
$time = date('Y-m-d H:i:s');
echo "欢迎 {$fd}:{$name} 加入聊天室\n";
$members = $this->getMembers();
$membersObj = array_combine(array_column($members, 'id'), array_column($members, 'name'));
foreach ($this->table as $member) {
if ($member['id'] === $fd) {
// 将'加入成功'的消息 与 '当前聊天室的人员信息' 推送给当前用户
$res = ['code' => 'add_success', 'data' => [
'time' => $time, 'msg' => "欢迎 {$name} 加入聊天室",
'members' => $members, 'membersObj' => $membersObj,
'self' => $member
]];
}else{
// 将当前用户 '加入的消息' 推送给聊天室 的其他用户
$res = ['code' => 'new_member', 'data' => [
'time' => $time, 'msg' => "欢迎 {$name} 加入聊天室",
'user' => $user
]];
}
$this->server->push($member['id'], json_encode($res));
}
}
private function send(int $fd, string $msg)
{
$user = $this->table->get($fd);
echo "{$user['name']} send : $msg\n";
$time = date('Y-m-d H:i:s');
foreach ($this->table as $member) {
// 只将消息推送个 已注册昵称 且 连接有效的聊天室用户
if($member['name'] && $this->server->isEstablished($member['id'])){
if ($member['id'] == $fd) {
// 将'发送成功'的消息推送给当前用户
echo "send to: {$member['id']} {$member['name']} success" . "\n";
$res = ['code' => 'send_success', 'data' => [
'time' => $time, 'msg' => $msg, 'author' => $fd
]];
}else{
// 将当前用户 '发送的消息' 推送给聊天室 的其他用户
echo "send to: {$member['id']} {$member['name']} success" . "\n";
$res = ['code' => 'new_message', 'data' => [
'time' => $time, 'msg' => $msg, 'author' => $fd
]];
}
$this->server->push($member['id'], json_encode($res));
}
}
}
}
$chat = new ChatServer('0.0.0.0', 9501);
$chat->run();
Html
ChatRoom
欢迎 来到 高雷 的 网页聊天室
Script
var msgIpt = document.getElementById('message'),
sendBtn = document.getElementById('send_btn'),
msgList = document.getElementById('msg-list'),
nickname, members, membersObj,mouseIn = false;
// 用户加入之前需要填写昵称,昵称显示在用户列表
nickname = getNick()
document.getElementById('nickname').innerText = nickname;
var wsAddress = 'ws://127.0.0.1:9501',
socket = new WebSocket(wsAddress),
mine;
socket.onopen = function (evt) {
addNotice('连接成功');
register();
};
socket.onclose = function (evt) {
console.log("Disconnected");
};
socket.onerror = function (evt, e) {
console.log('Error occured: ' + evt.data);
};
socket.onmessage = recv;
// 获取用户的昵称
function getNick() {
var nick = (prompt('请输入您的昵称') || '').replace(/(^\s*)|(\s*$)/g, "");
if (nick.length > 0) {
addNotice('连接中...')
return nick;
}
return getNick();
}
// JSON 对象 转 json 字符串
function toJSON(data) {
return JSON.stringify(data);
}
// 注册并加入聊天室
function register() {
socket.send(toJSON({action: 'join', value: nickname}));
}
// 监听 发送按钮
sendBtn.onclick = function () {
var msg = msgIpt.value;
if (msgIpt.value.length < 1) {
return msgIpt.focus();
}
socket.send(toJSON({action: 'send', value: msg}));
msgIpt.value = '';
}
// 监听消息发送组合键
document.onkeydown = function (oEvent) {
var e = event || window.event || arguments.callee.caller.arguments[0];
if ((e.keyCode === 13) && (e.ctrlKey || e.metaKey)) {
sendBtn.click();
}
}
msgList.onmouseover = function () {
mouseIn = true;
}
msgList.onmouseleave = function () {
mouseIn = false;
}
// 接受处理信息
function recv(evt) {
try {
var response = JSON.parse(evt.data)
switch (response.code) {
case "add_success":
return addSuccess(response.data)
case "new_member":
return newMember(response.data)
case 'new_message':
return newMessage(response.data)
case 'send_success':
return sendSuccess(response.data)
case 'someone_out':
return someoneOut(response.data)
}
} catch (e) {
// 打印错误信息
console.log([e, evt]);
}
}
// 加入聊天室成功,将已有的人员写入列表
function addSuccess(data) {
console.log(['addSuccess', data])
addNotice(data.time + ' ' + data.msg)
mine = data.self;
members = data.members;
membersObj = data.membersObj;
console.log([mine, members, membersObj])
members.forEach(function (v) {
addMemberLine(v)
})
}
// 消息发送成功
function sendSuccess(data) {
console.log(['sendSuccess', data])
addMessageLine(data, 1)
}
// 接受到新的消息
function newMessage(data) {
console.log(['newMessage', data])
addMessageLine(data, 2)
}
// 接收到有新的人加入到聊天室
function newMember(data) {
console.log(['newMember', data])
addNotice(data.time + ' ' + data.msg)
members.push(data.user);
membersObj[data.user.id] = data.user.name;
console.log([mine, members, membersObj])
addMemberLine(data.user);
}
// 有人退出聊天室
function someoneOut(data) {
console.log(['someoneOut', data])
addNotice(data.time + ' ' + data.msg)
removeMemberLine(data.member_id)
}
// 添加 提示信息
function addNotice(msg) {
var dom = document.createElement('div');
dom.className = 'notice';
dom.innerText = msg;
msgList.appendChild(dom);
}
// 添加一行消息展示
function addMessageLine(data, type) {
if(!membersObj[data.author]){
return;
}
var box = document.createElement('div'),
author = document.createElement('div'),
msg = document.createElement('div'),
name = document.createElement('span'),
time = document.createElement('span');
box.className = type === 1 ? 'mine' : 'other';
author.className = 'author';
msg.className = 'msg';
name.className = 'name';
time.className = 'time';
name.innerText = membersObj[data.author];
time.innerText = data.time;
author.appendChild(name);
author.innerHTML += ':'
author.appendChild(time);
msg.innerText = data.msg;
box.appendChild(author);
box.appendChild(msg);
msgList.appendChild(box);
if(mouseIn){
return;
}
msgList.scrollTop = msgList.scrollHeight;
}
// 新的人加入,将用户人员信息写入列表
function addMemberLine(user) {
var memberList = document.getElementById('members'),
item = document.createElement('div');
if (user.id == mine.id) {
item.className = 'member-item self'
} else {
item.className = 'member-item'
}
item.innerText = user.name;
item.id = 'member_' + user.id;
memberList.appendChild(item);
}
// 有人退出网页,在用户列表将其移除
function removeMemberLine(id) {
var line = document.getElementById('member_'+id);
if(line)line.remove();
}
Css
* {margin: 0;padding: 0}
html, body {height: 100%;}
body {
display: flex;justify-content: center;align-items: center;background: #000
}
.chart-room {
width: 1000px;height: 100%;max-height: 800px;margin: auto;background: #333;box-shadow: 0 0 10px #222;
padding: 5px;color: #888;display: flex;flex-wrap: wrap;align-items: center;
}
.chart-room > div {
width: 100%;background: #333;
}
/* 头部信息展示部分 */
.room-header {
height: 80px;border-bottom: 1px solid #888;
}
.room-header #nickname {
color: red
}
/* 消息展示部分 */
.room-body {
display: flex;width: 100%;height: calc(100% - 185px);
}
.room-body #members {
width: 150px;background: #2d3a4c;padding: 8px 0;overflow-y: scroll;
}
.room-body #members .member-item {
line-height: 20px;padding: 0 5px;font-size: 13px;
}
.room-body #members .member-item.self {
color: #f54cd8;
}
.room-body #members .member-item:hover {
background: #384153;
}
.room-body #msg-list {
width: calc(100% - 150px);overflow-y: scroll;padding: 5px;
}
.room-body #msg-list > * {margin-bottom: 10px}
.room-body #msg-list .notice{
text-align: center;font-size: 13px;
}
.room-body #msg-list .other,.room-body #msg-list .mine{
display: flex;
}
.room-body #msg-list .msg,.room-body #msg-list .author{
display: flex;align-items: center;padding: 5px;line-height: 27px;
}
.room-body #msg-list .author .time{font-size: 12px}
.room-body #msg-list .msg{
background: #666;border-radius: 3px;font-size: 13px;line-height: 17px;
max-width: 200px;padding: 3px 10px;height: auto;
}
.room-body #msg-list .msg::selection{
background: #336666;color: red;
}
/* 其他人发送的消息*/
.room-body #msg-list .other{flex-direction: row}
/* 我自己发送的消息 */
.room-body #msg-list .mine{flex-direction: row-reverse}
/* 发送消息部分 */
.room-footer {
height: 100px;border-top: 1px solid #888;display: flex;align-items: center;
}
.room-footer #message {
resize: none;width: calc(100% - 180px);height: 89px;line-height: 20px;border-top: none;
outline: none;padding: 5px;overflow-y: scroll;color: #888;caret-color: #aaa;
background: #333;
}
.room-footer #send_btn {
width: 180px;text-align: center;height: 100px;line-height: 100px;
user-select: none;background: #366;color: #ccc;position: relative;
}
.room-footer #send_btn:hover {
background: #355;
}
.room-footer #send_btn:active {
background: #344;
}
.room-footer #send_btn .notice {
position: absolute;bottom: 61px;width: 100%;font-size: 12px;color: #999;
background: none;height: 20px;left: 0;
}
原文链接 Swoole + websocket 实现简易版网页聊天室