websocket
进行通信。websocket
是socket的封装,省去了通信上的HTTP协议转换上的麻烦.实验以发送html页面上的图片到服务器后端为例子.
服务端接收图片后,开启本地端口为10086的服务,等待前端的连接.服务把前端发的图像url存在本地文件car.bmp.
import asyncio import websockets import urllib.request async def recv_user_msg(websocket): while True: url = await websocket.recv() urllib.request.urlretrieve(url,'car.bmp') await websocket.send('ok') async def run(websocket, path): while True: try: await recv_user_msg(websocket) except websockets.ConnectionClosed: print("ConnectionClosed...", path) break if __name__ == '__main__': print("127.0.0.1:10086 websocket...") asyncio.get_event_loop().run_until_complete(websockets.serve(run, "127.0.0.1", 10086)) asyncio.get_event_loop().run_forever()
缺少module直接pip install安装解决.
pip install websockets pip install urllib
在页面上嵌入img标签,连接服务端,点击发送图片,图片发送至服务端,并且显示返回结果.
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>测试Socket——ws://127.0.0.1:10086</title> </head> <body> <img id = 'img' src="https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1598273151875&di=2823d5f7c3aa5e075bd785572e3e1561&imgtype=0&src=http%3A%2F%2Fimage.9game.cn%2F2019%2F8%2F8%2F90082743.jpg"/> <button onclick = "send_img()">发送图片</> <script type="text/javascript"> var socket; var ws = new WebSocket("ws://127.0.0.1:10086/test"); socket = ws; ws.onopen = function() { console.log('连接成功'); }; ws.onmessage = function(evt) { var received_msg = evt.data; alert('recv:' + received_msg + ' 发送完成'); }; ws.onclose = function() { s = '断开了连接' alert(s); }; function send_img() { image = document.getElementById('img'); socket.send(image.src); } </script> </body> </html>
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:mmqy2019@163.com进行举报,并提供相关证据,查实之后,将立刻删除涉嫌侵权内容。
长按识别二维码并关注微信
更方便到期提醒、手机管理