javascript – php ZMQ推送整合http

前端之家收集整理的这篇文章主要介绍了javascript – php ZMQ推送整合http前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我正在尝试使用PHP和本机zmq实现推送集成.我已经成功发送我的消息发送到服务器,但我的问题是我无法使用js Websocket()将消息推送到浏览器.我说WebSocket连接到’ws://127.0.0.1:8080 /’失败:WebSocket握手期间出错:状态行无效

这是我的客户代码

<?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>

请告诉我我错过了什么.谢谢.

解决方法

你不能将websocket连接到zmq套接字*,它们是不同的通信协议(websocket更像是传统的套接字,zmq套接字更像是一种增加额外功能的抽象).您需要在服务器上设置一种方法来接收websocket连接.

*您可以使用RAW套接字类型来完成这项工作,但这有点高级,除非您知道自己在做什么,否则不应该输入.

猜你在找的JavaScript相关文章