title: Connecting to a flask websocket using python
body: <p>What I'm trying to do may not be possible, but here it goes.</p>
  
  <p>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.</p>
  
  <p>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:</p>
  
  <pre><code>import socket
  s = socket.socket()
  host = socket.gethostname()
  port = 12345
  s.connect((host, port))
  </code></pre>
  
  <p>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.</p>
  
  <p>Any help (or just telling me that it's not possible) would be much appreciated!</p>
  
  <p>===== EDIT =====</p>
  
  <p>So, with the help of @Aravind, I've come up with a simple example for a client server solution using only python:</p>
  
  <p>Server:</p>
  
  <pre><code>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)
  </code></pre>
  
  <p>Client:</p>
  
  <pre><code>import websocket
  from websocket import create_connection
  ws = create_connection("ws://127.0.0.1:12345/echo")
  ws.send("hello world")
  ws.recv()
  </code></pre>
  
  <p>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.</p>