首页 > 解决方案 > 如何通过 php 客户端发送 websocket 升级标头

问题描述

我正在尝试升级我的 php 客户端以使用 websockets,但是,我收到错误:400 Bad Request发送标头时。(我的 ws 服务器在 node.js 中)

消息是输出的,$buf因为这是服务器发回的内容......(我认为)

我已经缩小了代码,所以它很容易阅读,我的真实代码有多个错误检查;)

完整错误:

HTTP/1.1 400 Bad Request
Connection: close
Content-Type: text/html
Content-Length: 11

客户

<?php

$host = "localhost";
$port = 8000;

$sock = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
socket_connect($sock, $host, $port));

$headers = "GET / HTTP/1.1\r\n";
$headers .= "Upgrade: websocket\r\n";
$headers .= "Connection: Upgrade\r\n";
$headers .= "Sec-WebSocket-Version: 13\r\n";
$headers .= "Sec-WebSocket-Key: i9riAfOgSsKwUlmLjIkGA==\r\n\r\n";

socket_write($sock, $headers, strlen($headers));
socket_recv($sock, $buf, 2045, MSG_WAITALL);
echo $buf;

简单的服务器

import WebSocket from "ws";
const wss = new WebSocket.Server({ port: 8000 });
wss.on("connection", (ws) => {
    console.log("connection recieved!");
});

标签: phphttpwebsockethttp-status-code-400handshake

解决方案


$Headers 中可能需要 "Host:....\r\n" 和 "Origin:...\r\n"


推荐阅读