无法在移动设备上打开 websocket [英] Can't open websocket on mobile devices

查看:93
本文介绍了无法在移动设备上打开 websocket的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用在我的 raspberry pi 上运行的服务器设置 websocket.以下代码从我在 here.

我围绕这个例子构建了一个完整的网页,允许我控制 gpio 并将消息发送到插入 pi 的串行设备.该网站和本示例都可以在我的笔记本电脑上完美运行(Windows 10 使用 Chrome 或 Firefox).

但是,当我从手机连接时(Android 5.0.1,使用 Chrome for android).它似乎永远不会打开套接字.在示例代码中,它只显示messages go here.

我的第一个想法是 android 上的 chrome 不支持 websockets,但我能够在这个站点上连接和回显消息 http://www.websocket.org/echo.html.所以看起来功能就在那里.

还有什么会阻止套接字打开?

pysocket.py

import tornado.httpserver导入 tornado.websocket导入 tornado.ioloop导入 tornado.web类 WSHandler(tornado.websocket.WebSocketHandler):def check_origin(self, origin):返回真定义打开(自我):打印新连接已打开"self.write_message("欢迎来到我的websocket!")def on_message(self, message):打印 '传入消息:', 消息self.write_message("你说:" + message)def on_close(self):打印连接已关闭..."application = tornado.web.Application([(r'/ws', WSHandler),])如果 __name__ == "__main__":http_server = tornado.httpserver.HTTPServer(application)http_server.listen(8888)tornado.ioloop.IOLoop.instance().start()

pysocket.php

<头><title>WebSockets with Python &龙卷风</title><meta charset="utf-8"/><style type="text/css">身体 {文本对齐:居中;最小宽度:500px;}</风格><script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script><脚本>$(函数(){变量 ws;var 记录器 = 函数(味精){var now = new Date();var sec = now.getSeconds();var min = now.getMinutes();var hr = now.getHours();$("#log").html($("#log").html() + "<br/>" + hr + ":" + min + ":" + sec + " ___ " + msg);//$("#log").animate({ scrollTop: $('#log')[0].scrollHeight}, 100);$('#log').scrollTop($('#log')[0].scrollHeight);}var 发送者 = 函数(){var msg = $("#msg").val();if (msg.length > 0)ws.send(msg);$("#msg").val(msg);}ws = new WebSocket("ws://raspberrypi-mike:8888/ws");ws.onmessage = 函数(evt){记录器(evt.data);};ws.onclose = 函数(evt){$("#log").text("连接已关闭...");$("#thebutton #msg").prop('disabled', true);};ws.onopen = function(evt) { $("#log").text("Opening socket...");};$("#msg").keypress(function(event) {if (event.which == 13) {发件人();}});$("#thebutton").click(function(){发件人();});});<身体><h1>WebSockets with Python &龙卷风</h1><div id="log" style="overflow:scroll;width:500px; height:200px;background-color:#ffeeaa; margin:auto; text-align:left">消息在这里</div><div style="margin:10px"><input type="text" id="msg" style="background:#fff;width:200px"/><input type="button" id="thebutton" value="发送"/>

<a href="http://lowpowerlab.com/blog/2013/01/17/raspberrypi-websockets-with-python-tornado/">www.LowPowerLab.com</a></html>

解决方案

为了使设备的主机名能够跨网络工作,设备必须公布自己的主机名或仅响应 DNS 查询以获取自己的主机名.

无论 Raspberry Pi 使用什么实现,您的笔记本电脑都支持它,但您的手机不支持.

因此,为了能够连接,您需要在 JavaScript 代码中将主机名 raspberrypi-mike 更改为 Raspberry Pi 的 IP 地址.

I am attempting to set up a websocket with server running on my raspberry pi. The following code is slightly modified from an example I found here.

I have built a whole webpage around this example allowing me to control gpio and send messages to a serial device plugged into the pi. Both that site and this example work perfectly from my laptop (windows 10 using Chrome or Firefox).

However when I connect from my phone (Android 5.0.1 using Chrome for android). It appears to never open the socket. In the example code it just displays "messages go here.

My first thought was the chrome on android didn't support websockets but I was able to connect and echo messages on this site http://www.websocket.org/echo.html. So it appears the functionality is there.

What else would prevent the socket from opening ?

pysocket.py

import tornado.httpserver
import tornado.websocket
import tornado.ioloop
import tornado.web

class WSHandler(tornado.websocket.WebSocketHandler):

  def check_origin(self, origin):
    return True

  def open(self):
    print 'New connection was opened'
    self.write_message("Welcome to my websocket!")

  def on_message(self, message):
    print 'Incoming message:', message
    self.write_message("You said: " + message)

  def on_close(self):
    print 'Connection was closed...'

application = tornado.web.Application([
  (r'/ws', WSHandler),
])

if __name__ == "__main__":
  http_server = tornado.httpserver.HTTPServer(application)
  http_server.listen(8888)
  tornado.ioloop.IOLoop.instance().start()

pysocket.php

<!doctype html>
<html>
  <head>
    <title>WebSockets with Python & Tornado</title>
    <meta charset="utf-8" />
    <style type="text/css">
      body {
        text-align: center;
        min-width: 500px;
      }
    </style>
    <script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
    <script>
      $(function(){
        var ws;
        var logger = function(msg){
          var now = new Date();
          var sec = now.getSeconds();
          var min = now.getMinutes();
          var hr = now.getHours();
          $("#log").html($("#log").html() + "<br/>" + hr + ":" + min + ":" + sec + " ___ " +  msg);
          //$("#log").animate({ scrollTop: $('#log')[0].scrollHeight}, 100);
          $('#log').scrollTop($('#log')[0].scrollHeight);
        }

        var sender = function() {
          var msg = $("#msg").val();
          if (msg.length > 0)
            ws.send(msg);
          $("#msg").val(msg);
        }

        ws = new WebSocket("ws://raspberrypi-mike:8888/ws");
        ws.onmessage = function(evt) {

          logger(evt.data);
        };
        ws.onclose = function(evt) { 
          $("#log").text("Connection was closed..."); 
          $("#thebutton #msg").prop('disabled', true);
        };
        ws.onopen = function(evt) { $("#log").text("Opening socket..."); };

        $("#msg").keypress(function(event) {
          if (event.which == 13) {
             sender();
           }
        });

        $("#thebutton").click(function(){
          sender();
        });
      });
    </script>
  </head>

  <body>
    <h1>WebSockets with Python & Tornado</h1>
    <div id="log" style="overflow:scroll;width:500px; height:200px;background-color:#ffeeaa; margin:auto; text-align:left">Messages go here</div>

    <div style="margin:10px">
      <input type="text" id="msg" style="background:#fff;width:200px"/>
      <input type="button" id="thebutton" value="Send" />
    </div>

    <a href="http://lowpowerlab.com/blog/2013/01/17/raspberrypi-websockets-with-python-tornado/">www.LowPowerLab.com</a>
  </body>
</html>

解决方案

For the hostnames of the devices to work across network, a device has to advertise its own hostname or just responding to DNS queries for its own hostname.

Whatever implementation the Raspberry Pi is using, your laptop is supporting it, but your phone isn't.

So, to be able to connect, you need to change your hostname raspberrypi-mike to your Raspberry Pi's IP address, inside your JavaScript code.

这篇关于无法在移动设备上打开 websocket的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆