我尝试用PHP制作一个WebSocket。客户端是一个javascript应用程序。我可以将数据从WebSocket发送到客户端。但是,如果我尝试将信息从客户端发送到服务器,则该消息看起来像“ ^ @u¹‰;WØë#Wƒ«!Ï«=“。 我尝试将json_decode /设置为strval,但是它不起作用。我也在Javascript中尝试过使用(socket.send(“ abc”))发送普通邮件。和一个JSON objectsocket.send(JSON.stringify({“ abc”:“ abv”))));
以下是php代码:
<?php
/**
* Created by PhpStorm.
* User: rfur
* Date: 07.09.2018
* Time: 09:23
*/
// not my code
$address = '10.10.20.212';
$port = 1414;
$server = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
socket_set_option($server, SOL_SOCKET, SO_REUSEADDR, 1);
socket_bind($server, $address, $port);
socket_listen($server);
$client = socket_accept($server);
$request = socket_read($client, 5000);
preg_match('#Sec-WebSocket-Key: (.*)\r\n#', $request, $matches);
$key = base64_encode(pack(
'H*',
sha1($matches[1] . '258EAFA5-E914-47DA-95CA-C5AB0DC85B11')
));
$headers = "HTTP/1.1 101 Switching Protocols\r\n";
$headers .= "Upgrade: websocket\r\n";
$headers .= "Connection: Upgrade\r\n";
$headers .= "Sec-WebSocket-Version: 13\r\n";
$headers .= "Sec-WebSocket-Accept: $key\r\n\r\n";
socket_write($client, $headers, strlen($headers));
while (true) {
sleep(1);
$content = 'Now: ' . time();
$response = chr(129) . chr(strlen($content)) . $content;
socket_write($client, $response);
echo "socket_read: " . socket_read($client ,1024) . "\n";
socket_write($client, $response);
echo "var_dump socket_read: " . var_dump(socket_read($client,1024)) .
socket_write($client, $response);"\n";
echo "json_decode socket_read: " . json_decode(socket_read($client,1024)) . "\n";
socket_write($client, $response);
echo "var_dump json_decode socket_read: " . var_dump(json_decode(socket_read($client,1024))) . "\n";
}
这是客户端代码:
<html>
<body>
<div id="root"></div>
<script>
var host = 'ws://10.10.20.212:1414/websockets.php';
var socket = new WebSocket(host);
socket.onmessage = function(e) {
document.getElementById('root').innerHTML = e.data;
socket.send("abc");
};
</script>
</body>
</html>
输出如下:
socket_read: �ƒÛ¸b¹z
string(9) "�ƒPÂMn2¡"
var_dump socket_read:
json_decode socket_read:
NULL
var_dump json_decode socket_read: