我試圖實現推動整合使用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>
請不要告訴我我錯過了什麼。謝謝。