您好,登錄后才能下訂單哦!
本篇內(nèi)容主要講解“php如何實現(xiàn)聊天室功能”,感興趣的朋友不妨來看看。本文介紹的方法操作簡單快捷,實用性強。下面就讓小編來帶大家學(xué)習(xí)“php如何實現(xiàn)聊天室功能”吧!
php實現(xiàn)聊天室功能的方法:首先創(chuàng)建前端代碼;然后在PHP后端文件中通過創(chuàng)建“private function initSocket(){...}”等方法實現(xiàn)聊天室功能即可。
本文操作環(huán)境:windows7系統(tǒng)、PHP7.1版,DELL G3電腦
php怎么實現(xiàn)聊天室功能?
一、功能界面
二、具體代碼實現(xiàn)
1、前端代碼如下
<!DOCTYPE html> <html> <head> <meta charset="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="css/reset.min.css"> <link rel="stylesheet" href="css/style.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> <div> <div> <div style="padding: 20px 29px;height: auto;"> <div class="" style="font: 400 13.3333px Arial;font-weight: 400;">在線人數(shù):<span id="numbers">0</span> 人 </div> </div> <ul> </ul> </div> <div> <div><span>Tips: <span>PHP之websocket聊天室</span></span></div> <div class="chat active-chat" data-chat="person1" style="height: auto;border-width: 0px;padding: 10px;height: 483px; padding: 10px;overflow-y: auto;scrollTop: 100px"> </div> <div> <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 send" onclick="send()"></a> </div> </div> </div> </div> <script src="js/index.js"></script> <script> var uname = prompt('請輸入用戶名', 'user' + uuid(8, 16)); var avatar = ['bo-jackson.jpg', 'dog.png', 'drake.jpg', 'louis-ck.jpeg', 'michael-jordan.jpg', 'thomas.jpg']; if (avatar[Math.round(Math.random() * 10)]) { var headerimg = "img/" + avatar[Math.round(Math.random() * 10)]; } else { var headerimg = "img/" + avatar[0]; } // 創(chuàng)建一個 websocket 連接 var ws = new WebSocket("ws://127.0.0.1:1238"); // websocket 創(chuàng)建成功事件 ws.onopen = function () { var data = "系統(tǒng)消息:建立連接成功"; console.log(data); }; // websocket 接收到消息事件 ws.onmessage = function (e) { var data = JSON.parse(e.data); switch (data.type) { case 'handShake': console.log(data.msg); //發(fā)送用戶登錄 var user_info = {'type': 'login', 'msg': uname, 'headerimg': headerimg}; sendMsg(user_info); break; case 'login': userList(data.user_list); systemMessage('系統(tǒng)消息: ' + data.msg + ' 已上線'); break; case 'logout': userList(data.user_list); if (data.msg.length > 0) { systemMessage('系統(tǒng)消息: ' + data.msg + ' 已下線'); } break; case 'user': messageList(data); break; case 'system': systemMessage(); break; } } // websocket 錯誤事件 ws.onerror = function () { var data = "系統(tǒng)消息 : 出錯了,請退出重試."; alert(data); }; function confirm(event) { var key_num = event.keyCode; if (13 == key_num) { send(); } else { return false; } } function systemMessage(msg) { var html = `<div> <span>` + msg + `</span> </div>`; var active_chat = document.querySelector('div.active-chat'); var oldHtml = active_chat.innerHTML; active_chat.innerHTML = oldHtml + html; active_chat.scrollTop = active_chat.scrollHeight; } function send() { var msg = document.querySelector("input#input-value").value; var reg = new RegExp("\r\n", "g"); msg = msg.replace(reg, ""); sendMsg({type: "user", msg: msg}); document.querySelector("input#input-value").value = ""; } function sendMsg(msg) { var data = JSON.stringify(msg); ws.send(data); } function userList(user) { var html = ''; for (var i = 0; i < user.length; i++) { html += `<li data-chat="person1"> <img src="` + user[i].headerimg + `" alt=""/> <span>` + user[i].username + `</span> <span>` + user[i].login_time + `</span> <span style="color: green;font-size: 7px;">在線</span> </li>`; } document.querySelector('ul.people').innerHTML = html; document.querySelector('span#numbers').innerHTML = user.length; } function messageList(data) { if (data.from == uname) { var html = `<div> <img src="` + data.headerimg + `" alt=""/> <div class="bubble me">` + data.msg + `</div> </div>`; } else { var html = `<div> <img src="` + data.headerimg + `" alt=""/> <div class="bubble you">` + data.msg + `</div> </div>`; } var active_chat = document.querySelector('div.active-chat'); var oldHtml = active_chat.innerHTML; active_chat.innerHTML = oldHtml + html; active_chat.scrollTop = active_chat.scrollHeight; } /** * 生產(chǎn)一個全局唯一ID作為用戶名的默認(rèn)值; * * @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]; } else { 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>
2、后端代碼如下
<?php /** * Created by PhpStorm. * User: 25754 * Date: 2019/4/23 * Time: 14:13 */ class socketServer { const LISTEN_SOCKET_NUM = 9; const LOG_PATH = "./log/"; private $_ip = "127.0.0.1"; private $_port = 1238; private $_socketPool = array(); private $_master = null; public function __construct() { $this->initSocket(); } private function initSocket() { try { //創(chuàng)建socket套接字 $this->_master = socket_create(AF_INET, SOCK_STREAM, SOL_TCP); // 設(shè)置IP和端口重用,在重啟服務(wù)器后能重新使用此端口; socket_set_option($this->_master, SOL_SOCKET, SO_REUSEADDR, 1); //綁定地址與端口 socket_bind($this->_master, $this->_ip, $this->_port); //listen函數(shù)使用主動連接套接口變?yōu)楸贿B接套接口,使得一個進程可以接受其它進程的請求,從而成為一個服務(wù)器進程。在TCP服務(wù)器編程中l(wèi)isten函數(shù)把進程變?yōu)橐粋€服務(wù)器,并指定相應(yīng)的套接字變?yōu)楸粍舆B接,其中的能存儲的請求不明的socket數(shù)目。 socket_listen($this->_master, self::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("server: {$this->_master} started,pid: {$pid}")); while (true) { try { $this->run(); } catch (Exception $e) { $this->debug(array("code: " . $e->getCode() . ", message: " . $e->getMessage())); } } } private function run() { $write = $except = NULL; $sockets = array_column($this->_socketPool, 'resource'); $read_num = socket_select($sockets, $write, $except, NULL); if (false === $read_num) { $this->debug(array('socket_select_error', $err_code = socket_last_error(), socket_strerror($err_code))); return; } foreach ($sockets as $socket) { if ($socket == $this->_master) { $client = socket_accept($this->_master); if ($client === false) { $this->debug(['socket_accept_error', $err_code = socket_last_error(), socket_strerror($err_code)]); continue; } //連接 $this->connection($client); } else { //接受數(shù)據(jù) $bytes = @socket_recv($socket, $buffer, 2048, 0); if ($bytes == 0) { $recv_msg = $this->disconnection($socket); } else { if ($this->_socketPool[(int)$socket]['handShake'] == false) { $this->handShake($socket, $buffer); continue; } else { $recv_msg = $this->parse($buffer); } } $msg = $this->doEvents($socket, $recv_msg); echo($msg); socket_getpeername ( $socket , $address ,$port ); $this->debug(array( 'send_success', json_encode($recv_msg), $address, $port )); $this->broadcast($msg); } } } /** * 數(shù)據(jù)廣播 * @param $data */ private function broadcast($data) { foreach ($this->_socketPool as $socket) { if ($socket['resource'] == $this->_master) { continue; } socket_write($socket['resource'], $data, strlen($data)); } } /** * 業(yè)務(wù)處理 * @param $socket * @param $recv_msg * @return string */ private function doEvents($socket, $recv_msg) { $msg_type = $recv_msg['type']; $msg_content = $recv_msg['msg']; $response = []; switch ($msg_type) { case 'login': $this->_socketPool[(int)$socket]['userInfo'] = array("username" => $msg_content, 'headerimg' => $recv_msg['headerimg'], "login_time" => date("h:i")); // 取得最新的名字記錄 $user_list = array_column($this->_socketPool, 'userInfo'); $response['type'] = 'login'; $response['msg'] = $msg_content; $response['user_list'] = $user_list; break; case 'logout': $user_list = array_column($this->_socketPool, 'userInfo'); $response['type'] = 'logout'; $response['user_list'] = $user_list; if ($nowUserSocket = @$this->_socketPool[(int)$socket]) { $response['msg'] = $nowUserSocket['userInfo']['username']; }else{ $response['msg'] = ''; } break; case 'user': $userInfo = $this->_socketPool[(int)$socket]['userInfo']; $response['type'] = 'user'; $response['from'] = $userInfo['username']; $response['msg'] = $msg_content; $response['headerimg'] = $userInfo['headerimg']; break; } return $this->frame(json_encode($response)); } /** * 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" . "Sec-WebSocket-Accept: " . $acceptKey . "\r\n\r\n"; // 寫入socket socket_write($socket, $upgrade, strlen($upgrade)); // 標(biāo)記握手已經(jīng)成功,下次接受數(shù)據(jù)采用數(shù)據(jù)幀格式 $this->_socketPool[(int)$socket]['handShake'] = true; socket_getpeername ( $socket , $address ,$port ); $this->debug(array( 'hand_shake_success', $socket, $address, $port )); //發(fā)送消息通知客戶端握手成功 $msg = array('type' => 'handShake', 'msg' => '握手成功'); $msg = $this->frame(json_encode($msg)); socket_write($socket, $msg, strlen($msg)); return true; } /** * 幀數(shù)據(jù)封裝 * @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); } else if ($len < 65025) { $s = dechex($len); $frame[1] = '7e' . str_repeat('0', 4 - strlen($s)) . $s; } else { $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); } /** * 接受數(shù)據(jù)解析 * @param $buffer * @return mixed */ private function parse($buffer) { $decoded = ''; $len = ord($buffer[1]) & 127; if ($len === 126) { $masks = substr($buffer, 4, 4); $data = substr($buffer, 8); } else if ($len === 127) { $masks = substr($buffer, 10, 4); $data = substr($buffer, 14); } else { $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); } // 提取 Sec-WebSocket-Key 信息 private function getKey($req) { $key = null; if (preg_match("/Sec-WebSocket-Key: (.*)\r\n/", $req, $match)) { $key = $match[1]; } return $key; } //加密 Sec-WebSocket-Key private function encry($req) { $key = $this->getKey($req); return base64_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, 'userInfo' => '', 'handShake' => false, '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]['username'], ); unset($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(self::LOG_PATH . 'websocket_debug.log', implode(' | ', $info) . "\r\n", FILE_APPEND); } } new socketServer();
到此,相信大家對“php如何實現(xiàn)聊天室功能”有了更深的了解,不妨來實際操作一番吧!這里是億速云網(wǎng)站,更多相關(guān)內(nèi)容可以進入相關(guān)頻道進行查詢,關(guān)注我們,繼續(xù)學(xué)習(xí)!
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關(guān)證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。