使用python连接到Flask Websocket [英] Connecting to a flask websocket using python

查看:99
本文介绍了使用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的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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