Python3 本地建立 websocket 服务器,本地访问正常,手机访问异常,请问可能是什么原因导致?

2020-01-15 17:22:43 +08:00
 black11black

大家好,我今天在本地做一些尝试,想把网页输入框的内容用 ws 实时推流回服务器

后台框架 aiohttp 前端用 jquery 简单梭了一个功能测试,很高兴功能一切正常

本地测试完成后,想测一下其他设备访问, 连接路由器,开放防火墙等等一系列操作以后,网页能加载成功,但 ws 连接失败, 本菜鸡比较懵逼,请问这可能是什么原因导致的? 有没有高手指点一下,谢谢!

=======================================================================

#目录结构

/testpath
   main.py
   /templates
       hello.html

非常简单的小 demo,前后端代码分别如下:

本地测试 127.0.0.1:8080,一切功能正常 使用其他电脑连接本地 192.168.0.101 提示 wserror,疯狂异常弹窗 到底咋回事?

======================================================================= 附带文字代码

import asyncio ,os ,aiohttp_jinja2 ,jinja2 ,aiohttp.web

@aiohttp_jinja2.template('hello2.html')
async def testhandle(request):
    return 
    
async def websocket_handler(request):
    print('Websocket connection starting')
    ws = aiohttp.web.WebSocketResponse()
    await ws.prepare(request)
    print('Websocket connection ready')

    async for msg in ws:
        if msg.type == aiohttp.WSMsgType.TEXT:
            print(repr(msg.data))

    print('Websocket connection closed')
    return ws

def main():
    loop = asyncio.get_event_loop()
    app = aiohttp.web.Application(loop=loop)
    aiohttp_jinja2.setup(app, loader=jinja2.FileSystemLoader('./templates'))
    app.router.add_route('GET', '/', testhandle)
    app.router.add_route('GET', '/ws', websocket_handler)
    aiohttp.web.run_app(app, host='0.0.0.0', port='8080')

if __name__ == '__main__':
    main()

======================================================================

<html>
<head>
<meta charset="UTF-8">
<title> Web sockets test </title>
<script src="http://code.jquery.com/jquery-1.9.1.js" type="text/javascript"></script>
<script type="text/javascript">
    // ws 部分
    ws = new WebSocket("ws://127.0.0.1:8080/ws"); 
    ws.onopen = function(event){alert("已经与服务器建立了连接\r\n 当前连接状态:"+this.readyState);};
    ws.onclose = function(event){alert("已经与服务器断开连接\r\n 当前连接状态:"+this.readyState);};
    ws.onerror = function(event){alert("WebSocket 异常!\r\n 当前连接状态:"+this.readyState);};
    // 有输入时增量上传
    var last_length = 0;
    var SendData = function(){
        var current_length = $("#test").val().length;
        ws.send($("#test").val().substring(last_length,current_length));
        last_length = current_length;
    }
    // 监听输入事件
    $(document).on("input propertychange",".inp",SendData);
</script>
</head>

<body>
    <textarea id="test" class="inp" placeholder="please input"></textarea>
</body></html>
877 次点击
所在节点    问与答
3 条回复
ysc3839
2020-01-15 17:27:36 +08:00
你该不会是网页中写死了 127.0.0.1 吧?那自然连不上呀。
ZavierXu
2020-01-15 17:28:58 +08:00
@ysc3839 HHH 一针见血啊
black11black
2020-01-15 17:29:36 +08:00
@ysc3839
233 感谢感谢

我自己瞅了半天不知道啥毛病,还奇怪 /都刷出来了 /ws 咋出不来,睁眼瞎

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/638207

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX