Skip to content
Advertisement

How can I connect a Python websocket client to my Spring endpoint?

I’m new to Python and I’m trying to connect to a service that I currently have up running in Spring.

On the server-side I have a custom Handshake handler in place by extending DefaultHandshakeHandler and overriding the determineUser method, where I then extract the user information. However, when the request comes in, there is nothing to extract.

What I would like to know is, how do I send this information over with the request?

Here is my basic Python client.

import  websocket
import stomper

headers = {}
#### have also tried with headers = Authorization : Bearer + token ####

uri = "ws://localhost:[port]/ws"

def on_msg(ws,msg):
    print(msg)

def on_error(ws,err):
    print(err)

def on_closed(ws):
    print(#Closed#)

def on_open(ws):
    ws.send("CONNECTnaccept-version:1.0,1.1,2.0nnx00n")
    sub = stomper.subscribe("/user/topic/my-end-point", "username", ack="auto")
    ws.send(sub)

ws = websocket.WebSocketApp(uri, header=headers, on_message=on_msg, on_error=on_error, on_close=on_closed)
ws.on_open = on_open
ws.run.forever()

When I run this, I get the following:

--- request header ---
GET /ws HTTP/1.1
Upgrade: websocket
Host: localhost:[port]
Origin: http://localhost[port]
Sec-WebSocket-Key: key
Sec-WebSocket-version: 13
Connection: Upgrade

--- response header ---
HTTP/1.1 101 Switching Protocols
Date: date
Connection: Upgrade
Sec-WebSocket-Accept: key
Server: server-info
Upgrade: WebSocket

send: b'\x81...
CONNECTED
version: 1.1
session: session_id
server: server-info

It then times out after 60 seconds.

What can I try next?

Advertisement

Answer

I should probably update this.

I was missing the authentication token parameter in the url string.

It works as expected now.

User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement