PHP实现websocket长链接流程详解
简介
目前PHP实现web socket 都是使用框架集成来实现,比如hyperf,swoft,或者是安装swoole 扩展来实现websocket,那么有没有PHP本身就能够实现的呢,答案当然有,Let’s go.
函数介绍
服务端
stream_socket_server — Create an Internet or Unix domain server socket
可以帮我创建网络链接具柄,参数如下
stream_socket_server(
string $address,
int &$error_code = null,
string &$error_message = null,
int $flags = STREAM_SERVER_BIND | STREAM_SERVER_LISTEN,
?resource $context = null
): resource|false
客户端
stream_socket_client — Open Internet or Unix domain socket connection
连接句柄
stream_socket_client(
string $address,
int &$error_code = null,
string &$error_message = null,
?float $timeout = null,
int $flags = STREAM_CLIENT_CONNECT,
?resource $context = null
): resource|false
简单运用
<?php //服务端$socket = stream_socket_server("tcp://0.0.0.0:8000", $errno, $errstr);if (!$socket) { echo "$errstr ($errno)<br />\n";} else { while ($conn = stream_socket_accept($socket)) { //循环 等待链接 fwrite($conn, 'The local time is ' . date('n/j/Y g:i a') . "\n");//成功链接输出以上内容 大致为:The local time is 3/22/2023 11:13 am fclose($conn); //断开连接 } fclose($socket); //断开socket}?><?php //客户端$fp = stream_socket_client("tcp://0.0.0.0:8000", $errno, $errstr, 30);if (!$fp) { echo "$errstr ($errno)<br />\n";} else { fwrite($fp, "GET / HTTP/1.0\r\nHost: www.example.com\r\nAccept: */*\r\n\r\n"); while (!feof($fp)) { echo fgets($fp, 1024); } fclose($fp);}?>
解释
上面的事例,只能在服务器之间调用,而且每次链接都会断开,一旦需要使用服务就需要不断的进行连接,不断的进行三次握手很浪费资源,那么能不能实现一个呢,No Code No BB.
JsDemo
// 创建websocketws = new WebSocket("ws://"+domain+"/"+port);// 当socket连接打开时,输入用户名ws.onopen = function(){}; //自定义 连接建立时处理操作,比如IM系统登陆信息操作// 当有消息时根据消息类型显示不同信息ws.onmessage = function(){};// 操作服务端发来的消息 ws.onclose = function() { console.log("连接关闭,定时重连"); connect();//重新连接};ws.onerror = function() { console.log("出现错误");};
PHP实现三次握手
$socket = stream_socket_server('tcp://'.$ipServer.':'.$portNumber, $errno, $errstr);while($conn = @stream_socket_accept($socket,$nbSecondsIdle)){ $message= fread($conn, 1024); send($conn,$message); //@todo //连接成功,有要保持连接,用来接收客户端发送过来的数据包 这里可以把这个连接$conn 保存在内存当中,通过Select or Swoole 事件去loop fputs ($conn, "OK\n");}function send($socket,$buffer){ $Sec_WebSocket_Key = ''; if (\preg_match("/Sec-WebSocket-Key: *(.*?)\r\n/i", $buffer, $match)) { $Sec_WebSocket_Key = $match[1]; } $new_key = \base64_encode(\sha1($Sec_WebSocket_Key . "258EAFA5-E914-47DA-95CA-C5AB0DC85B11", true)); $handshake_message = "HTTP/1.1 101 Switching Protocols\r\n" ."Upgrade: websocket\r\n" ."Sec-WebSocket-Version: 13\r\n" ."Connection: Upgrade\r\n" ."Sec-WebSocket-Accept: " . $new_key . "\r\n"; $handshake_message .= "\r\n"; var_dump($handshake_message);//打印握手信息,然后发送给客户端,建立完整连接 //socket_write($socket,$handshake_message); $len = @\fwrite($socket, $handshake_message); return 0;}
到此这篇关于PHP实现web socket长链接流程详解的文章就介绍到这了,更多相关PHP web socket长链接内容请搜索以前的文章或继续浏览下面的相关文章希望大家以后多多支持!