這篇文章主要為大家詳細(xì)介紹了php實現(xiàn)聊天室功能,文中示例代碼介紹的非常詳細(xì),零基礎(chǔ)也能參考此文章,感興趣的小伙伴們可以參考一下。
站在用戶的角度思考問題,與客戶深入溝通,找到岑鞏網(wǎng)站設(shè)計與岑鞏網(wǎng)站推廣的解決方案,憑借多年的經(jīng)驗,讓設(shè)計與互聯(lián)網(wǎng)技術(shù)結(jié)合,創(chuàng)造個性化、用戶體驗好的作品,建站類型包括:成都網(wǎng)站建設(shè)、網(wǎng)站制作、企業(yè)官網(wǎng)、英文網(wǎng)站、手機端網(wǎng)站、網(wǎng)站推廣、域名注冊、網(wǎng)頁空間、企業(yè)郵箱。業(yè)務(wù)覆蓋岑鞏地區(qū)。
1、在前端使用Ajax定時輪詢訪問php腳本,php再進(jìn)行查詢聊天數(shù)據(jù)進(jìn)行返回給前端,最后前端將其進(jìn)行渲染;
代碼示例:
聊天室 在線用戶列表prepare("select * from chat where is_login = '1'"); $rs->execute(); while($row = $rs->fetch()){ echo ''.$row['username'].'
'; } ?>
connect("localhost",11211); if(isset($_POST['content'])){ $con['username'] = $_SESSION["username"]; $con['content'] = $_POST["content"]; $data = $mem->get('chat'); $data[] = $con; $mem->set("chat",$data,0,0); } $mem->close(); */ if(isset($_POST['content'])){ session_start(); $filename = date("Ymd",time()).".txt"; if(file_exists($filename)){ $content = file_get_contents($filename); $data = json_decode($content,true); $con['username'] = $_SESSION["username"]; $con['content'] = $_POST["content"]; $data[] = $con; $file = fopen($filename,"w"); fwrite($file,json_encode($data)); fclose($file); }else{ $file = fopen($filename,"w"); $con['username'] = $_SESSION["username"]; $con['content'] = $_POST["content"]; $data[] = $con; fwrite($file,json_encode($data)); fclose($file); } } ?>
$old[0]){ //echo json_encode($new['data']); //print_r($new); echo '2222222222'.'
'; } //echo '
11111111111111111111111111111111111111111111111111111111111111111111'; usleep(1000); } */ /*set_time_limit(0); $mem = new Memcache; $mem->connect("localhost",11211); $count = count($mem->get("chat")); $com = true; //$mem->delete('chat'); if($_POST['msg'] == "one"){ exit(json_encode($mem->get("chat"))); } if($_POST['msg'] == "break"){ $com = false; } $time1 = time(); while(true){ if($com){ $data = $mem->get("chat"); if(count($data)>$count){ echo json_encode($data); break; } usleep(300); }else{ break; } } $mem->close();*/ set_time_limit(0); $filename = date("Ymd",time()).".txt"; if(file_exists($filename)){ $content = file_get_contents($filename); $data = json_decode($content,true); $count = count($data); // echo $count;die; if($_POST['msg'] == "one"){ exit(json_encode($data)); } while(true){ $contents = file_get_contents($filename); $datas = json_decode($contents,true); $counts = count($datas); if($counts>$count){ echo json_encode($datas); break; } usleep(300); } }else{ $file = fopen($filename,"w"); $con['username'] = "系統(tǒng)消息"; $con['content'] = "歡迎來到EPGO聊天室"; $data[] = $con; fwrite($file,json_encode($data)); fclose($file); exit(json_encode($data)); } ?>
2、使用WebSocket和服務(wù)器進(jìn)行長連接,來實現(xiàn)聊天功能。
客戶端代碼:
websocket聊天室
服務(wù)端代碼:
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接套接口,使得一個進(jìn)程可以接受其它進(jìn)程的請求,從而成為一個服務(wù)器進(jìn)程。在TCP服務(wù)器編程中l(wèi)isten函數(shù)把進(jìn)程變?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) { //聯(lián)系我 } /** * 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)聊天室功能的具體代碼,如果在日常工作遇到這個問題,希望你能通過這篇文章解決問題。如果想了解更多相關(guān)內(nèi)容,歡迎關(guān)注創(chuàng)新互聯(lián)行業(yè)資訊頻道!