swoole聊天室

服务端:

<?php
class Chat
{
const HOST = '0.0.0.0';//ip地址 0.0.0.0代表接受所有ip的访问
const PART = 8080;//端口号

private $server = null;//单例存放websocket_server对象

public $roles = [
'郭靖','杨过','洪七公','尹志平','赵志敬','丘处机','欧阳锋','一灯大师','黄药师'
];

public function __construct()
{
//实例化swoole_websocket_server并存储在我们Chat类中的属性上,达到单例的设计
$this->server = new swoole_websocket_server(self::HOST, self::PART);
//监听连接事件
$this->server->on('open', [$this, 'onOpen']);
//监听接收消息事件
$this->server->on('message', [$this, 'onMessage']);
//监听关闭事件
$this->server->on('close', [$this, 'onClose']);
//设置允许访问静态文件
$this->server->set([
'document_root' => '/www/chat1',//这里传入静态文件的目录
'enable_static_handler' => true//允许访问静态文件
]);


//开启服务
$this->server->start();
}

/**
* 连接成功回调函数
* @param $server
* @param $request
*/
public function onOpen($server, $request)
{
echo $request->fd . '连接了' . PHP_EOL;//打印到我们终端
$server->push($request->fd,json_encode(['no' => $request->fd, 'msg' =>'']));
}

/**
* 接收到信息的回调函数
* @param $server
* @param $frame
*/
public function onMessage($server, $frame)
{
$role = $this->getRole($frame->fd);
echo $role. '来了,说:' . $frame->data . PHP_EOL;//打印到我们终端
foreach ($server->connections as $fd) {//遍历TCP连接迭代器,拿到每个在线的客户端id
//将客户端发来的消息,推送给所有用户,也可以叫广播给所有在线客户端
$msg = $frame->data;
$server->push($fd, json_encode(['no' => $frame->fd,'role'=>$role, 'msg' => $msg]));
}
}

public function getRole($fd)
{
$roles = count($this->roles);
$role = ($fd < $roles) ? $this->roles[$fd] : $this->roles[$fd%$roles];
var_dump($role);
return $role;
}

/**
* 断开连接回调函数
* @param $server
* @param $fd
*/
public function onClose($server, $fd)
{
echo $fd . '走了' . PHP_EOL;//打印到我们终端
}

}

$obj = new Chat();

  客户端

<!doctype html>

<html>

<head>

<meta charset="utf-8">

<title>聊天室</title>

<script src="http://libs.baidu.com/jquery/1.9.1/jquery.min.js"></script>

</head>

<body>
<style>
.right {
color: blue;
display:block;
float:right;
100%;
}


</style>

<div style=" 500px; margin:0 auto;">
<div class="log" id='scrolldIV' style="height:500px;border: 2px solid #ccc;line-height: 1.5em;overflow:auto" >

=======聊天室======

</div>

<!--<input type="button" value="连接" onClick="link()">-->
<input type="hidden" value="" id="fd">
<!--<input type="button" value="断开" onClick="dis()">-->

<div >
<input type="text" id="text">

<input type="button" value="发送" onClick="send()" id="submit">
</div>

</div>


<script>


$(document).keydown(function(event){
if(event.keyCode==13){
$("#submit").click();
}
});


$(function () {
$("#text").focus();
link();
})

function link() {

var url = 'ws://192.168.33.60:8080';

socket = new WebSocket(url);

socket.onopen = function (evt) {
log1('<div>连接成功</div>')
}

socket.onmessage = function (msg) {
var data = $.parseJSON(msg.data)
if(data.msg.length <= 0){
$("#fd").val(data.no);
} else {
log(data);
}
      
     
        var div = document.getElementById('scrolldIV');
        div.scrollTop = div.scrollHeight;

}

socket.onclose = function () {
log1('<div>断开连接</div>')
}

}

function dis() {

socket.close();

socket = null;

}

function log1(data) {
$('.log').append(data);
}
function log(data) {
var nowFd = $("#fd").val();
console.log(data);
var role;
if(data['no'] == nowFd){
role ="我";
$('.log').append("<div class='right'>" + role+":"+ data['msg'] + '</div>');
} else {

$('.log').append("<div >" + data.role+": "+data['msg'] + '</div>');
}


}

function send() {
var text = $('#text').val();
if(text.length > 0){
socket.send(text);
$("#text").val('');
}


$("#text").focus();

}

function send2() {

var json = JSON.stringify({'type': 'php', 'msg': $('#text2').attr('value')})

socket.send(json);

}

</script>

</body>

</html>

  

服务端 启动

php Chat.php

访问客户端的html 浏览器打开

参考 https://www.jianshu.com/p/ac77f05bee56

原文地址:https://www.cnblogs.com/brady-wang/p/11526305.html