How to use PHP to develop online chat function
In today's Internet era, instant messaging has become an indispensable part of people's daily lives. The development of online chat functions has become an important requirement for many websites and applications. This article will introduce how to use PHP to develop a simple online chat function and provide code samples for reference.
Using PHP to develop online chat functions mainly involves two aspects of technology: the construction of front-end pages and the implementation of real-time communication. The following is a simple example to demonstrate how to develop online chat functionality using PHP.
First, we need to create a front-end page to display chat records and input boxes.
<!DOCTYPE html> <html> <head> <title>在线聊天</title> <style> .container { border: 1px solid #ccc; height: 400px; width: 500px; padding: 10px; overflow-y: scroll; } </style> </head> <body> <div class="container" id="chatContainer"></div> <input type="text" id="messageInput"> <input type="button" value="发送" onclick="sendMessage()"> </body> <script> function updateChat(data) { document.getElementById('chatContainer').innerHTML += '<p>' + data + '</p>'; } function sendMessage() { var message = document.getElementById('messageInput').value; // 向服务器发送消息的代码 } </script> </html>
The above code creates a container for displaying chat records, an input box for entering messages, and a send button for sending messages. Received messages can be added to the chat history through JavaScript's updateChat function.
In order to realize the real-time communication function, we will use PHP and WebSocket technology.
First, create a PHP script for the WebSocket server on the server side.
<?php $host = 'localhost'; $port = '8080'; $null = NULL; $server = socket_create(AF_INET, SOCK_STREAM, SOL_TCP); socket_set_option($server, SOL_SOCKET, SO_REUSEADDR, 1); socket_bind($server, 0, $port); socket_listen($server); $clients = array($server); while (true) { $changed = $clients; socket_select($changed, $null, $null, 0, 10); if (in_array($server, $changed)) { $socket_new = socket_accept($server); $clients[] = $socket_new; $header = socket_read($socket_new, 1024); performHandshaking($header, $socket_new, $host, $port); socket_getpeername($socket_new, $ip); $response = mask(json_encode(array('type' => 'system', 'message' => $ip . ' connected.'))); sendMessage($response); $found_socket = array_search($server, $changed); unset($changed[$found_socket]); } foreach ($changed as $changed_socket) { while (socket_recv($changed_socket, $buf, 1024, 0) >= 1) { $received_text = unmask($buf); $tst_msg = json_decode($received_text); $user_name = $tst_msg->name; $user_message = $tst_msg->message; $response_text = mask(json_encode(array('type' => 'usermsg', 'name' => $user_name, 'message' => $user_message))); sendMessage($response_text); break 2; } $buf = @socket_read($changed_socket, 1024, PHP_NORMAL_READ); if ($buf === false) { $found_socket = array_search($changed_socket, $clients); socket_getpeername($changed_socket, $ip); unset($clients[$found_socket]); $response = mask(json_encode(array('type' => 'system', 'message' => $ip . ' disconnected.'))); sendMessage($response); } } } socket_close($server); function sendMessage($message) { global $clients; foreach ($clients as $changed_socket) { @socket_write($changed_socket, $message, strlen($message)); } return true; } function unmask($text) { $length = ord($text[1]) & 127; if ($length == 126) { $masks = substr($text, 4, 4); $data = substr($text, 8); } elseif ($length == 127) { $masks = substr($text, 10, 4); $data = substr($text, 14); } else { $masks = substr($text, 2, 4); $data = substr($text, 6); } $text = ""; for ($i = 0; $i < strlen($data); ++$i) { $text .= $data[$i] ^ $masks[$i % 4]; } return $text; } function mask($text) { $b1 = 0x80 | (0x1 & 0x0f); $length = strlen($text); if ($length <= 125) { $header = pack('CC', $b1, $length); } elseif ($length > 125 && $length < 65536) { $header = pack('CCn', $b1, 126, $length); } elseif ($length >= 65536) { $header = pack('CCNN', $b1, 127, $length); } return $header . $text; } function performHandshaking($receved_header, $client_conn, $host, $port) { $headers = array(); $lines = preg_split("/ /", $receved_header); foreach ($lines as $line) { $line = rtrim($line); if (preg_match('/A(S+): (.*)z/', $line, $matches)) { $headers[$matches[1]] = $matches[2]; } } $sec_key = $headers['Sec-WebSocket-Key']; $sec_accept = base64_encode(sha1($sec_key . "258EAFA5-E914-47DA-95CA-C5AB0DC85B11", true)); $upgrade = "HTTP/1.1 101 Web Socket Protocol Handshake " . "Upgrade: websocket " . "Connection: Upgrade " . "WebSocket-Origin: $host " . "WebSocket-Location: ws://$host:$port/demo/shout.php " . "Sec-WebSocket-Accept:$sec_accept "; socket_write($client_conn, $upgrade, strlen($upgrade)); } ?>
The above code implements a simple WebSocket server that can accept and send messages.
In addition, we also need to add a WebSocket client JavaScript code to the front-end page for real-time communication with the server.
var socket = new WebSocket('ws://localhost:8080'); socket.onopen = function() { updateChat("连接已建立"); }; socket.onmessage = function(e) { updateChat(e.data); }; socket.onclose = function() { updateChat("连接已关闭"); }; function sendMessage() { var message = document.getElementById('messageInput').value; socket.send(message); document.getElementById('messageInput').value = ''; } function updateChat(data) { document.getElementById('chatContainer').innerHTML += '<p>' + data + '</p>'; }
In the above code, we process the received message through the WebSocket event listener and add it to the chat record. The sendMessage function is used to send messages to the server.
So far, we have implemented a simple online chat function based on PHP. Through the above sample code, I believe readers can have a preliminary understanding of how to use PHP to develop online chat functions, and can expand and optimize the functions according to their own needs.
The above is the detailed content of How to use PHP to develop online chat function. For more information, please follow other related articles on the PHP Chinese website!