2015-08-16 15 views
7

我試圖實現推動整合使用PHP和本地zmq。我已經成功發送我的消息發送到服務器,但我的問題是我無法使用js Websocket()將消息推送到瀏覽器。我說:WebSocket連接到 'WS://127.0.0.1:8080 /' 失敗:WebSocket的握手過程中的錯誤:無效的狀態行PHP ZMQ推動整合在http

這裏是我的客戶端代碼:

<?php 
try { 
    function send($data) { 
     $context = new ZMQContext(); 
     $push = new ZMQSocket($context, ZMQ::SOCKET_PUSH); 
     $push->connect("tcp://localhost:5555"); 

     $push->send($data); 
    }  

    if(isset($_POST["username"])) { 
     $envelope = array(
     "from" => "client", 
     "to" => "owner", 
     "msg" => $_POST["username"] 
    ); 
     send(json_encode($envelope)); # send the data to server 
    } 
} 
catch(Exception $e) { 
    echo $e->getMessage(); 
} 

?> 

客戶

這裏是我的服務器:

$context = new ZMQContext(); 

$pull = new ZMQSocket($context, ZMQ::SOCKET_PULL); 
$pull->bind("tcp://*:5555"); #this will be my pull socket from client 

$push = new ZMQSocket($context, ZMQ::SOCKET_PUSH); 
$push->bind("tcp://127.0.0.1:8080"); # this will be the push socket to owner 

while(true) { 
    $data = $pull->recv(); # when I receive the data decode it 
    $parse_data = json_decode($parse_data); 

    if($parse_data["to"] == "owner") { 
     $push->send($parse_data["msg"]); # forward the data to the owner 
    } 
    printf("Recieve: %s.\n", $data); 
} 

,這裏是我的owner.php我期待中的數據直通的WebSocket在瀏覽器中發送:

<html> 
<head> 
    <meta charset="UTF-8"> 
    <title></title> 
</head> 
<body> 
    <h2>Message</h2> 
    <ul id="messagelog"> 
    </ul> 
    <script> 
     var logger = document.getElementById("messagelog"); 
     var conn = new WebSocket("ws://127.0.0.1:8080"); # the error is pointing here. 

     conn.onOpen = function(e) { 
      console.log("connection established"); 
     } 
     conn.onMessage = function(data) { 
      console.log("recieved: ", data); 
     } 

     conn.onError = function(e) { 
      console.log("connection error:", e); 
     } 
     conn.onClose = function(e) { 
      console.log("connection closed~"); 
     } 
    </script> 
</body> 

請不要告訴我我錯過了什麼。謝謝。

回答

1

無法將websocket連接到zmq套接字*,它們是不同的通信協議(websocket更像是一個傳統的套接字,而zmq套接字更像是一種提供額外功能的抽象)。您需要在服務器上設置一個方法來接收WebSocket連接。

*您可能能夠使用RAW套接字類型進行此項工作,但這有點更先進,除非您知道自己在做什麼,否則不應輸入。

2

您根本沒有建立協議通信。您設法接收到該消息,但是您從未通過解析併發送適當的響應來確認您的服務器確實是WebSocket服務器。

由於您已經在使用PHP和ZeroMQ,所以最簡單的方法是使用Mongrel2,這是一種能夠理解WebSocket協議並將其傳遞到編碼爲tnetstring的ZeroMQ端點(類似於json的編碼格式,瑣碎解析)。

另一種解決方案是在您的代碼中完全支持WebSocket協議 - 這超出了這個問題和答案的範圍。