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套接字类型来完成这项工作,但这有点高级,除非您知道自己在做什么,否则不应该输入.

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐


js中event的用法
js中能调用python吗
js中split的用法
js怎么设置边框样式
js中截取字符串的方法
js中innerhtml的用法
javascript的成熟分类方式有哪些
js中document是什么意思
js怎样让div中的文字居中
js中怎样定义一个对象
javascript的成熟分类介绍
js中parseint什么意思
js中字符串如何排序
void在js中是什么意思
js中如何定义函数
js中arguments是什么意思
js中什么是同步和异步
js中如何sleep一秒
js中ui函数是什么意思
js中如何遍历数组