使用python连接到Flask Websocket

编程入门 行业动态 更新时间:2024-10-12 01:30:59
本文介绍了使用python连接到Flask Websocket的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我试图做的事情可能无法实现,但是就可以了.

What I'm trying to do may not be possible, but here it goes.

我已经在Flask上玩了一段时间了,并且已经使用flask-socketio创建了多个测试,允许用户在通过Web浏览器访问页面时进行即时通信.

I've been playing around with Flask for a while now, and have created several tests using flask-socketio, allowing users to communicate instantly when accessing the page via a web browser.

但是,我想知道当使用套接字模块从Python本身连接到服务器时,这种事情是否可行.在同一系统中,连接到使用套接字模块托管的Python套接字的过程很简单:

However, I was wondering if that sort of thing is possible when connecting to the server from Python itself, using the socket module. Connecting to a socket in Python that is hosted using the socket module, from the same system, is as simple as:

import socket s = socket.socket() host = socket.gethostname() port = 12345 s.connect((host, port))

然而,经过一两个小时的研究和实验,我无法弄清楚如何使用这种代码来连接烧瓶中的websocket设置.

However after an hour or two of research and experimentation, I cannot work out how to use this kind of code to connect to a websocket setup within flask.

任何帮助(或只是告诉我这是不可能的)将不胜感激!

Any help (or just telling me that it's not possible) would be much appreciated!

=====编辑=====

===== EDIT =====

因此,在@Aravind的帮助下,我提出了一个仅使用python的客户端服务器解决方案的简单示例:

So, with the help of @Aravind, I've come up with a simple example for a client server solution using only python:

服务器:

from flask import Flask from flask_sockets import Sockets app = Flask(__name__) sockets = Sockets(app) @sockets.route('/echo') def echo_socket(ws): while not ws.closed: message = ws.receive() print(message) ws.send(message)

客户:

import websocket from websocket import create_connection ws = create_connection("ws://127.0.0.1:12345/echo") ws.send("hello world") ws.recv()

我现在意识到,我试图做的事情已经在多个不同的地方多次解释过,我只是没有将所有内容拼凑在一起.希望这将对像我一样对websocket感到困惑的其他人有所帮助.

I realise now that what I was attempting to do had been explained multiple times in multiple different places, I just hadn't put the pieces together. Hopefully this will help anyone else who was as confused by websockets as I was.

推荐答案

import websocket from websocket import create_connection ws = create_connection("127.0.0.1:12345") #ws.close() for closing #ws.send()enter code here #ws.recv() #pip install websocket-client

更多推荐

使用python连接到Flask Websocket

本文发布于:2023-11-23 13:04:34,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1621547.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:连接到   python   Websocket   Flask

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!