Python3 本地建立 websocket 服务器,本地访问正常,手机访问异常,请问可能是什么原因导致?
資深大佬 : black11black 62
大家好,我今天在本地做一些尝试,想把网页输入框的内容用 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("已经与服务器建立了连接rn 当前连接状态:"+this.readyState);}; ws.onclose = function(event){alert("已经与服务器断开连接rn 当前连接状态:"+this.readyState);}; ws.onerror = function(event){alert("WebSocket 异常!rn 当前连接状态:"+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>
大佬有話說 (3)