Connecting to a flask websocket using python

2020-07-22 17:42发布

问题:

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

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.

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))

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 =====

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

Server:

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)

Client:

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

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.

回答1:

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