simboyd
simboyd

Reputation: 93

Flask webapp with chat client (using websockets to another server)

Currently, I have a dynamic website that runs on Flask and I'd like to implement a chat client in the back-end that utilizes websockets that will connect to an external server. So, for example, I'd like to start a websocket to this external chat server when the logged-in user visits the "/chat" route.

Then, I'll handle sending/receiving messages with JavaScript on the page that POSTs a JSON object to another route, such as "/send_msg" while constantly checking for new messages by GETing from "/receive_msg".

The problem is that every single tutorial I've seen on the web (including questions on SO) have been about local websockets where the flask app itself acts as a chat server. And using python's built-in socket module is no good (I think) because I don't see a way to keep it open while the user is on the page and then close()-ing it when the user leaves the page. Is there any way to do this for an external server at all? If so, how do I go about doing this? Thanks! <3

Upvotes: -2

Views: 584

Answers (1)

Joran Beasley
Joran Beasley

Reputation: 113930

you are mixing your technology terms up I think

Flask is a webframework (there are some libraries that can offer websockets here), generally speaking this has nothing to do with websockets

It serves HTML/JS/CSS... you would use js to connect to your websocket server as follows

let ws = new WebSocket("ws://my.funky.ws/url")
ws.on_message = (data)=>{
  console.log("Got a websocket message1!!!:",data)
}
ws.on_close = ()=>console.log("Closed websocket connection!")
ws.on_open = () => console.log("Opened websocket server connection successfully!")

you run a websocket server, the javascript (or non-javascript) clients connect to (python-websocket-server is a pretty easy one to use iirc), but this is typically a seperate application from your flask server, (it can still import sqlalchemy models or functions or whatever))

if you really want just ajax calls to posts/gets to check for messages you would use a database table of some sort, that you then put new messages into and query for new messages periodically... but that is not a websocket server... socket servers have no concept of historical state... you only see messages that are sent while you are listening for them ...

Upvotes: 0

Related Questions