首页 > 作文

php+websocket 实现聊天室

更新时间:2023-04-08 11:16:15 阅读: 评论:0

一、配置
开启socket组建,否则会报 fatal error: call to undefined function socket_create() 错误
1、打开php.ini配置文件,搜索 extension=php_sockets.dll,把前面的‘;’分号删掉。修改之后重启服务。
注意:如果php版本多,一定要注意使用的哪个版本就要取修改哪个版本的php.ini文件,wamp开启socket需要apache和php下面的php.ini一起修改,而phpstudy只需要修改一个php.ini.

2、检查socket组建是否开启
运行phpinfo.php查看,如果sockets support => enabled,就说明开启成功了。

3、设置cmd可以运行php文件
在“我的计算机->属性->高级系统设置->高级->环境变量”,在用户变量的path添加一条,指向php的路径(注意版本要一致),在环境变量里的path也需要添加一条,跟上面一样

4、测试socket和php是否配置成功
在项目下新建一个名叫start.php的文件

 if(extension_loaded('sockets')){      echo "1";    }el{      echo "0";    }

在cmd里输入 php d:\phpstudy\www\start.php,如果输出1,则说明配置正确,如果输出0,则配置错误,需要仔细重新配置

二、实现流程

前端实现比较简单,难点在后台,其逻辑如下:php主要就是接收加密key并返回其中完成套接字的创建和握手操作

服务端的流程:
1、挂起一个socket套接字进程,等待连接
2、有socket连接之后,遍历套接字数组
3、没有握手的,进行握手操作,已经握手的,则把接收的数据解析并写入缓冲区进行输出。

三、前端代码

<!doctype html><html lang="en"><head><meta chart="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1"><title>websocket聊天室</title><link href="https://fonts.googleapis.com/css?family=source+sans+pro:400,600" rel="stylesheet"><link rel="stylesheet" href="/static/index/css/ret.min.css"><link rel="stylesheet" href="/static/index/css/chat.css"><link rel="stylesheet" href="/static/index/layui/layer/theme/default/layer.css"><style>.message img {float: left;width: 40px;height: 40px;margin-right: 12px;border-radius: 50%;}.you {margin-left: 60px;margin-top: -39px;}.me-header {float: right !important;margin-right: 0 !important;}.me {margin-right: 60px;margin-top: -39px;}.active-chat::-webkit-scrollbar, .left::-webkit-scrollbar {width: 2px;}</style></head><body><div class="wrapper"><div class="container"><div class="left"><div class="top" style="padding: 20px 29px;height: auto;"><div class="" style="font: 400 13.3333px arial;font-weight: 400;">在线人数:<span id="numbers">0</span> 人</div></div><ul class="people"></ul></div><div class="right"><div class="top"><span>tips: <span class="name">php之websocket聊天室</span></span></div><div class="chat active-chat" data-chat="person1"st数字的成语yle="height: auto;border-width: 0px;padding: 10px;height: 483px; padding: 10px;overflow-y: auto;scrolltop: 100px"></div><div class="write"><a href="javascript:;" class="write-link attach"></a><input type="text" id="input-value" onkeydown="confirm(event)"/><a href="javascript:;" class="write-link smiley"></a><a href="javascript:;" class="write-link nd" onclick="nd()"></a></div></div></div></div><script src="/static/index/js/jquery-1.11.3.min.js"></script><script src="/static/index/js/chat.js"></script><script src="/static/index/layui/layer/layer.js"></script><script>var uname = "ur" + uuid(8, 11);layer.open({title: '您的用户名如下',content: uname,clobtn: 0,yes: function (index, layero) {layer.clo(index);}});// 随机选出一个头像var avatar = ['a1.jpg', 'a2.jpg', 'a3.jpg', 'a4.jpg', 'a5.jpg', 'a6.jpg', 'a7.jpg', 'a8.jpg', 'a9.jpg', 'a10.jpg'];if (avatar[math.round(math.random() * 10)]) {var headerimg = "img/" + avatar[math.round(math.random() * 10)];} el {var headerimg = "img/" + avatar[0];}var ws = null;// 创建websocket连接connect();function connect() {// 创建一个 websocket 连接  ws://ip:端口号ws = new websocket("ws://127.0.0.1:1234");// 连接状态 1已建立连接console.log(ws.readystate)//  连接建立时触发ws.onopen = onopen;// 客户端接收服务端数据时触发ws.onmessage = onmessage;// 连接关闭时触发ws.onclo = onclo;//  通信发生错误时触发ws.onerror = onerror;}// 通信建立成功 function onopen(){var data = "系统消息:建立连接成功";console.log(data);}// 接收客户端的数据,发送数据function onmessage(e){var data = json.par(e.data);console.log(data)switch (data.type) {ca 'handshake'://首次登录,发送登陆数据var ur_info = {'type': 'login', 'msg': uname, 'headerimg': headerimg};ndmsg(ur_info);break;ca 'login':urlist(data.ur_list);systemmessage('系统消息: ' + data.msg + ' 已上线');break;ca 'logout':urlist(data.ur_list);if (data.msg.length > 0) {systemmessage('系统消息: ' + data.msg + ' 已下线');}break;ca 'ur':messagelist(data);break;ca 'system':systemmessage();break;}}function onclo(){console.log("连接关闭,定时重连");connect();}// websocket 错误事件function onerror(){var data = "系统消息 : 出错了,请退出重试.";console.log(data);}function confirm(event) {var key_num = event.keycode;if (13 == key_num) {nd();} el {return fal;}}// 发送数据function nd() {var msg = document.querylector("input#input-value").value;var reg = new regexp("\r\n", "g");msg = msg.replace(reg, "");ndmsg({type: "ur", msg: msg});document.querylector("input#input-value").value = "";}// 发送数据function ndmsg(msg) {var data = json.stringify(msg);ws.nd(data);}// 追加数据 上下线的系统消息function systemmessage(msg) {var html = `<div class="conversation-start"><span>` + msg + `</span></div>`;var active_chat = document.querylector('div.active-chat');var oldhtml = active_chat.innerhtml;active_chat.innerhtml = oldhtml + html;active_chat.scrolltop = active_chat.scrollheight;}// 追加从服务端返回的数据 左侧在线人数列表function urlist(ur) {var html = '';for (var i = 0; i < ur.length; i++六年级日记大全) {html += `<li class="person" data-chat="person1"><img src="` + ur[i].headerimg + `" alt=""/><span class="name">` + ur[i].urname + `</span><span class="time">` + ur[i].login_time + `</span><span class="preview" style="color: green;font-size: 7px;">在线</span></li>`;}document.querylector('ul.people').innerhtml = html;document.querylector('span#numbers').innerhtml = ur.length;}// 右侧聊天记录列表function messagelist(data) {// 判读是不是自己发送的消息,对应的样式不同if (data.from == uname) {   // 如果当前用户名和feom的用户名相同,就说明时自己发送的消息var html = `<div class="message"><img class="me-header" src="` + data.headerimg + `" alt=""/><div class="bubble me">` + data.msg + `</div></div>`;} el {// 别人发送的信息列表var html = `<div class="message"><img src="` + data.headerimg + `" alt=""/><div class="bubble you">` + data.msg + `</div></div>`;}var active_chat = document.querylector('div.active-chat');var oldhtml = active_chat.innerhtml;active_chat.innerhtml = oldhtml + html;active_chat.scrolltop = active_chat.scrollheight;}/*** 生产一个全局唯一id作为用户名的默认值;** @param len* @param radix* @returns {string}*/function uuid(len, radix) {var chars = '0123456789abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyz'.split('');var uuid = [], i;radix = radix || chars.length;if (len) {for (i = 0; i < len; i++) uuid[i] = chars[0 | math.random() * radix];} el {var r;uuid[8] = uuid[13] = uuid[18] = uuid[23] = '-';uuid[14] = '4';for (i = 0; i < 36; i++) {if (!uuid[i]) {r = 0 | math.random() * 16;uuid[i] = chars[(i == 19) ? (r & 0x3) | 0x8 : r];}}}return uuid.join('');}</script></body></html>

四、后端代码

<?php/*** created by phpstorm.* ur: 25754* date: 2019/4/23* time: 14:13*/class socketrver{const listen_socket_num = 9;const log_path = "./log/";  //日志private $_ip = "127.0.0.1"; //ipprivate $_port = 1234;  //端口 要和前端创建websocket连接时的端口号一致private $_socketpool = array(); //socket池,即存放套接字的数组private $_master = null;    //创建的套接字对象public function __construct(){$this->initsocket();}// 创建websocket连接private function initsocket(){try {//创建socket套接字$this->_master = socket_create(af_inet, sock_stream, sol_tcp);// 设置ip和端口重用,在重启服务器后能重新使用此端口;socket_t_option($this->_master, sol_socket, so_reuaddr, 1);//绑定地址与端口socket_bind($this->_master, $this->_ip, $this->_port);//listen函数使用主动连接套接口变为被连接套接口,使得一个进程可以接受其它进程的请求,从而成为一个服务器进程。在tcp服务器编程中listen函数把进程变为一个服务器,并指定相应的套接字变为被动连接,其中的能存储的请求不明的socket数目。socket_listen($this->_master, lf::listen_socket_num);} catch (exception $e) {$this->debug(array("code: " . $e->getcode() . ", message: " . $e->getmessage()));}//将socket保存到socket池中  (将套接字放入数组)默认把当前用户放在第一个$this->_socketpool[0] = array('resource' => $this->_master);$pid = getmypid();$this->debug(array("rver: {$this->_master} started,pid: {$pid}"));}// 挂起进程遍历套接字数组,对数据进行接收、处理、发送public function run(){// 死循环  直到socket断开while (true) {try {$write = $except = null;// 从数组中取出resource列$sockets = array_column($this->_socketpool, 'resource');/* $sockets 是一个存放文件描述符的数组。$write 是监听是否客户端写数据,传入null是不关心是否有写变化$except 是$sockets里面要派粗话的元素,传入null是监听全部最后一个参数是超时时间,0立即结束 n>1则最多n秒后结束,如遇某一个连接有新动态,则提前返回  null如遇某一个连接有新动态,则返回*/// 接收套接字数字,监听他们的状态就是有新消息到或有客户端连接/断开时,socket_lect函数才会返回,继续往下执行$read_num = socket_lect($sockets, $write, $except, null);if女工假 (fal === $read_num) {$this->debug(array('socket_lect_error', $err_code = socket_last_error(), socket_strerror($err_code)));return;}// 遍历套接字数组foreach ($sockets as $socket) {// 如果有新的连接进来if ($socket == $this->_master) {// 接收一个socket连接$client = socket_accept($this->_master);if ($client === fal) {$this->debug(['socket_accept_error', $err_code = socket_last_error(), socket_strerror($err_code)]);continue;}//连接 并放到socket池中$this->connection($client);} el {//接收已连接的socket数据,返回的是从socket中接收的字节数。// 第一个参数:socket资源,第二个参数:存储接收的数据的变量,第三个参数:接收数据的长度$bytes = @socket_recv($socket, $buffer, 2048, 0);// 如果接收的字节数为0if ($bytes == 0) {// 断开连接$recv_msg = $this->disconnection($socket);} el {// 判断有没有握手,没有握手进行握手,已经握手则进行处理if ($this->_socketpool[(int)$socket]['handshake'] == fal) {// 握手$this->handshake($socket, $buffer);continue;} el {// 解析客户端传来的数据$recv_msg = $this->par($buffer);}}// echo "<pre>";// 业务处理,组装返回客户端的数据格式$msg = $this->doevents($socket, $recv_msg);// print_r($msg);socket_getpeername ( $socket  , $address ,$port );$this->debug(array('nd_success',json_encode($recv_msg),$address,$port));// 把服务端返回的数据写入套接字$this->broadcast($msg);}}} catch (exception $e) {$this->debug(array("code: " . $e->getcode() . ", message: " . $e->getmessage()));}}}/*** 数据广播* @param $data*/private function broadcast($data){foreach ($this->_socketpool as $socket) {if ($socket['resource'] == $this->_master) {continue;}// 写入套接字socket_w电视剧永远的忠诚rite($socket['resource'], $data, strlen($data));}}/*** 业务处理,在这可以对数据库进行操作,并返回客户端数据;根据不同类型,组装不同格式的数据* @param $socket* @param $recv_msg 客户端传来的数据* @return string*/private function doevents($socket, $recv_msg){$msg_type = $recv_msg['type'];$msg_content = $recv_msg['msg'];$respon = [];//echo "<pre>";switch ($msg_type) {ca 'login英语培训机构迈格森':// 登陆上线信息$this->_socketpool[(int)$socket]['urinfo'] = array("urname" => $msg_content, 'headerimg' => $recv_msg['headerimg'], "login_time" => date("h:i"));// 取得最新的名字记录$ur_list = array_column($this->_socketpool, 'urinfo');$respon['type'] = 'login';$respon['msg'] = $msg_content;$respon['ur_list'] = $ur_list;//print_r($respon);break;ca 'logout':// 退出信息$ur_list = array_column($this->_socketpool, 'urinfo');$respon['type'] = 'logout';$respon['ur_list'] = $ur_list;$respon['msg'] = $msg_content;//print_r($respon);break;ca 'ur':// 发送的消息$urinfo = $this->_socketpool[(int)$socket]['urinfo'];$respon['type'] = 'ur';$respon['from'] = $urinfo['urname'];$respon['msg'] = $msg_content;$respon['headerimg'] = $urinfo['headerimg'];//print_r($respon);break;}return $this->frame(json_encode($respon));}/*** socket握手* @param $socket* @param $buffer  客户端接收的数据* @return bool*/public function handshake($socket, $buffer){$acceptkey = $this->encry($buffer);$upgrade = "http/1.1 101 switching protocols\r\n" ."upgrade: websocket\r\n" ."connection: upgrade\r\n" ."c-websocket-accept: " . $acceptkey . "\r\n\r\n";// 将socket写入缓冲区socket_write($socket, $upgrade, strlen($upgrade));// 标记握手已经成功,下次接受数据采用数据帧格式$this->_socketpool[(int)$socket]['handshake'] = true;socket_getpeername ( $socket  , $address ,$port );$this->debug(array('hand_shake_success',$socket,$address,$port));//发送消息通知客户端握手成功$msg = array('type' => 'handshake', 'msg' => '握手成功');$msg = $this->frame(json_encode($msg));socket_write($socket, $msg, strlen($msg));return true;}/*** 帧数据封装* @param $msg* @return string*/private function frame($msg){$frame = [];$frame[0] = '81';$len = strlen($msg);if ($len < 126) {$frame[1] = $len < 16 ? '0' . dechex($len) : dechex($len);} el if ($len < 65025) {$s = dechex($len);$frame[1] = '7e' . str_repeat('0', 4 - strlen($s)) . $s;} el {$s = dechex($len);$frame[1] = '7f' . str_repeat('0', 16 - strlen($s)) . $s;}$data = '';$l = strlen($msg);for ($i = 0; $i < $l; $i++) {$data .= dechex(ord($msg{$i}));}$frame[2] = $data;$data = implode('', $frame);return pack("h*", $data);}/*** 解析客户端的数据* @param $buffer* @return mixed*/private function par($buffer){$decoded = '';$len = ord($buffer[1]) & 127;if ($len === 126) {$masks = substr($buffer, 4, 4);$data = substr($buffer, 8);} el if ($len === 127) {$masks = substr($buffer, 10, 4);$data = substr($buffer, 14);} el {$masks = substr($buffer, 2, 4);$data = substr($buffer, 6);}for ($index = 0; $index < strlen($data); $index++) {$decoded .= $data[$index] ^ $masks[$index % 4];}return json_decode($decoded, true);}//提取 c-websocket-key 信息并加密private function encry($req){$key = null;if (preg_match("/c-websocket-key: (.*)\r\n/", $req, $match)) {$key = $match[1];}// 加密return ba64_encode(sha1($key . '258eafa5-e914-47da-95ca-c5ab0dc85b11', true));}/*** 连接socket* @param $client*/public function connection($client){socket_getpeername ( $client  , $address ,$port );$info = array('resource' => $client,'urinfo' => '','handshake' => fal,'ip' => $address,'port' => $port,);$this->_socketpool[(int)$client] = $info;$this->debug(array_merge(['socket_connect'], $info));}/*** 断开连接* @param $socket* @return array*/public function disconnection($socket){$recv_msg = array('type' => 'logout','msg' => @$this->_socketpool[(int)$socket]['urinfo']['urname'],);unt($this->_socketpool[(int)$socket]);return $recv_msg;}/*** 日志* @param array $info*/private function debug(array $info){$time = date('y-m-d h:i:s');array_unshift($info, $time);$info = array_map('json_encode', $info);file_put_contents(lf::log_path . 'websocket_debug.log', implode(' | ', $info) . "\r\n", file_append);}}// 类外实例化$sk = new socketrver();// 运行$sk -> run();

五、运行php

建立start.bat文件,运行php,也可以在cmd里输入命令运行php

php ./socketrver.phppau

运行结果如下:

注意:start.bat要一直运行,如果关了,就表示socket也关了,就不能通信了,所有需要start.bat一直运行

项目地址:

本文发布于:2023-04-08 11:16:13,感谢您对本站的认可!

本文链接:https://www.wtabcd.cn/fanwen/zuowen/f42bddac8ba880fb0574eeeb311ad30e.html

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。

本文word下载地址:php+websocket 实现聊天室.doc

本文 PDF 下载地址:php+websocket 实现聊天室.pdf

标签:数据   客户端   消息   在线
相关文章
留言与评论(共有 0 条评论)
   
验证码:
Copyright ©2019-2022 Comsenz Inc.Powered by © 专利检索| 网站地图