PHP实现一个web socket长链接,行不行?

2023-04-1911:31:23后端程序开发Comments1,089 views字数 2455阅读模式

PHP实现web socket 都是使用框架集成来实现,比如hyperf,swoft,或者是安装swoole 扩展来实现websocket,那么有没有PHP本身就能够实现的呢,答案当然有,Let's go.文章源自菜鸟学院-https://www.cainiaoxueyuan.com/bc/36040.html

函数介绍

服务端文章源自菜鸟学院-https://www.cainiaoxueyuan.com/bc/36040.html

stream_socket_server — Create an Internet or Unix domain server socket文章源自菜鸟学院-https://www.cainiaoxueyuan.com/bc/36040.html

可以帮我创建网络链接句柄,参数如下文章源自菜鸟学院-https://www.cainiaoxueyuan.com/bc/36040.html

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文章源自菜鸟学院-https://www.cainiaoxueyuan.com/bc/36040.html

客户端文章源自菜鸟学院-https://www.cainiaoxueyuan.com/bc/36040.html

stream_socket_client — Open Internet or Unix domain socket connection文章源自菜鸟学院-https://www.cainiaoxueyuan.com/bc/36040.html

连接句柄文章源自菜鸟学院-https://www.cainiaoxueyuan.com/bc/36040.html

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文章源自菜鸟学院-https://www.cainiaoxueyuan.com/bc/36040.html

简单运用
<?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.文章源自菜鸟学院-https://www.cainiaoxueyuan.com/bc/36040.html

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("出现错误");};

 文章源自菜鸟学院-https://www.cainiaoxueyuan.com/bc/36040.html

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;}
文章源自菜鸟学院-https://www.cainiaoxueyuan.com/bc/36040.html
  • 本站内容整理自互联网,仅提供信息存储空间服务,以方便学习之用。如对文章、图片、字体等版权有疑问,请在下方留言,管理员看到后,将第一时间进行处理。
  • 转载请务必保留本文链接:https://www.cainiaoxueyuan.com/bc/36040.html

Comment

匿名网友 填写信息

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定