首頁 >後端開發 >php教程 >如何用 PHP 建置 WebSocket 伺服器?

如何用 PHP 建置 WebSocket 伺服器?

Susan Sarandon
Susan Sarandon原創
2024-12-07 01:01:10388瀏覽

How to Build a WebSocket Server in PHP?

如何在PHP 中建立WebSocket 伺服器

建立WebSocket 伺服器可能是一項具有挑戰性的任務,特別是當您遇到過時的程式碼或不完整的文檔時。以下是引導您完成整個流程的詳細解決方案:

伺服器端程式碼:

<?php

set_time_limit(0);
ob_implicit_flush();

$master = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
socket_set_option($master, SOL_SOCKET, SO_REUSEADDR, 1);
socket_bind($master, "localhost", 12345);
socket_listen($master, 20);

$sockets = array($master);
$users = array();

while (true) {
  $changed = $sockets;
  socket_select($changed, $write=NULL, $except=NULL, NULL);
  foreach ($changed as $socket) {
    if ($socket == $master) {
      $client = socket_accept($master);
      if ($client < 0) {
        echo "socket_accept() failed\n";
        continue;
      } else {
        connect($client);
      }
    } else {
      $bytes = @socket_recv($socket, $buffer, 2048, 0);
      if ($bytes == 0) {
        disconnect($socket);
      } else {
        $user = getuserbysocket($socket);
        if (!$user->handshake) {
          dohandshake($user, $buffer);
        } else {
          process($user, $buffer);
        }
      }
    }
  }
}

function connect($socket) {
  global $sockets, $users;
  $user = new User();
  $user->id = uniqid();
  $user->socket = $socket;
  array_push($users, $user);
  array_push($sockets, $socket);
  echo $socket." CONNECTED!\n";
}

function disconnect($socket) {
  global $sockets, $users;
  $found = null;
  $n=count($users);
  for ($i=0;$i<$n;$i++) {
    if ($users[$i]->socket == $socket) {
      $found = $i;
      break;
    }
  }
  if (!is_null($found)) {
    array_splice($users, $found, 1);
  }
  $index = array_search($socket, $sockets);
  socket_close($socket);
  echo $socket." DISCONNECTED!\n";
  if ($index>=0) {
    array_splice($sockets, $index, 1);
  }
}

function dohandshake($user, $buffer) {
  $headers = getheaders($buffer);
  $acceptkey = base64_encode(sha1($headers[4] . "258EAFA5-E914-47DA-95CA-C5AB0DC85B11",true));
  $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_write($user->socket, $upgrade, strlen($upgrade));
  $user->handshake = true;
  echo "Done handshaking...\n";
}

function getheaders($req) {
  $r=$h=$u=$c=$key=$protocol=$version=$o=$data=null;
  if (preg_match("/GET (.*) HTTP/", $req, $match)) {
    $r = $match[1];
  }
  if (preg_match("/Host: (.*)\r\n/", $req, $match)) {
    $h = $match[1];
  }
  if (preg_match("/Upgrade: (.*)\r\n/", $req, $match)) {
    $u = $match[1];
  }
  if (preg_match("/Connection: (.*)\r\n/", $req, $match)) {
    $c = $match[1];
  }
  if (preg_match("/Sec-WebSocket-Key: (.*)\r\n/", $req, $match)) {
    $key = $match[1];
  }
  if (preg_match("/Sec-WebSocket-Protocol: (.*)\r\n/", $req, $match)) {
    $protocol = $match[1];
  }
  if (preg_match("/Sec-WebSocket-Version: (.*)\r\n/", $req, $match)) {
    $version = $match[1];
  }
  if (preg_match("/Origin: (.*)\r\n/", $req, $match)) {
    $o = $match[1];
  }
  if (preg_match("/\r\n(.*?)$/", $req, $match)) {
    $data = $match[1];
  }
  return array($r,$h,$u,$c,$key,$protocol,$version,$o,$data);
}

function getuserbysocket($socket) {
  global $users;
  $found = null;
  foreach ($users as $user) {
    if ($user->socket == $socket) {
      $found = $user;
      break;
    }
  }
  return $found;
}

class User {
  var $id;
  var $socket;
  var $handshake;
}

?>

客戶端代碼:

var connection = new WebSocket('ws://localhost:12345');

connection.onopen = function () {
  connection.send('Ping');
};

connection.onerror = function (error) {
  console.log('WebSocket Error ' + error);
};

connection.onmessage = function (e) {
  console.log('Server: ' + e.data);
};

故障排除:

如果遇到錯誤訊息「Firefox無法與位於ws:// 的伺服器建立連線” localhost:12345/”,檢查以下內容:

  • 確保您的伺服器程式碼正在執行連接埠12345。客戶端程式碼是否連接到正確的主機名稱和連接埠。規格中概述的 WebSocket 握手過程.
  • 確保正確處理 WebSocket 幀和屏蔽。

以上是如何用 PHP 建置 WebSocket 伺服器?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn