4
似乎與PHP在線的大多數HTML5網絡套接字示例都使用套接字插件。是否可以在HTML5網頁套接字上使用stream_socket_server
?PHP流式套接字不支持HTML5套接字?
如果是,我試圖用PHP stream_socket_server
函數構建一個簡單的套接字服務器+客戶端。下面是代碼:
PHP套接字服務器:
<?php
$server = stream_socket_server("tcp://localhost:8080", $errno, $errorMessage);
if ($server === false) {
throw new UnexpectedValueException("Could not bind to socket: $errorMessage");
}
for (;;) {
$client = stream_socket_accept($server);
if ($client) {
echo 'Connection accepted from '.stream_socket_get_name($client, false) . "\n";
stream_copy_to_stream($client, $client);
}
}
HTML5的Web客戶端的Socket。
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Client Testing</title>
<script src="https://code.jquery.com/jquery-3.2.1.min.js" integrity="sha256-hwg4gsxgFZhOsEEamdOYGBf13FyQuiTwlAQgxVSNgt4=" crossorigin="anonymous"></script>
</head>
<body>
<button id="send">Testing button</button>
<script>
websocket = new WebSocket("ws://localhost:8080");
websocket.onopen = function(evt) { /* do stuff */ }; //on open event
websocket.onclose = function(evt) { /* do stuff */ }; //on close event
websocket.onmessage = function(evt) { /* do stuff */ }; //on message event
websocket.onerror = function(evt) { /* do stuff */ }; //on error event
$('#send').click(function(){
websocket.send("This is a testing message"); //send method
});
//websocket.close(); //close method
</script>
</body>
</html>
這是當我連接了回報:
WebSocket connection to 'ws://localhost:8080/' failed: Error during WebSocket handshake: net::ERR_INVALID_HTTP_RESPONSE
有什麼我錯過了?如何返回有效的HTTP響應?
最好是堅持使用開源測試庫,你沒有關注WebSocket的RFC的。 – Gntem