PHP和WebSockets

时间:2018-11-05 19:26:54

标签: javascript php websocket

我正在开始使用PHP和WebSockets。
我尝试建立WebSocket连接失败,

main.js

const protocol = (() => {
  let protocol = "ws";
  if (location.protocol === "https") {
    protocol += "s";
  }
  return protocol + ":";
})();
const currentPath = location.href.replace(location.protocol, protocol);
const socket = new WebSocket(`${currentPath}php/player-info.php`);

socket.addEventListener("open", e => {
  socket.send("Hello");
});

socket.addEventListener("message", e => {
  console.log(e.data);
});

player-info.php

<?php

set_time_limit(0);

$socket = socket_create(AF_INET, SOCK_STREAM, 0) || die("Couldn't create socket");
$result = socket_bind($socket, $_SERVER["PHP_SELF"], 500) || die("Couldn't bind to socket");
$spawn = socket_accept($socket) || die("Couldn't accept incoming connection");
$input = trim(socket_read($spawn, 1024) || die("Couldn't read input"));

$output = $input;
socket_write($spawn, $output, strlen($output)) || die("Couldn't write output");

socket_close($spawn);
socket_close($socket);

我基本上正在做的是打开与main.js链接的页面。
当我查看WebSocket网络流量时,会看到:

我在做什么错了?

0 个答案:

没有答案