Can't maintain active connection of phxsocket client with Phoenix server

Hey there,
I’ve setup the connection of phxsocket client with pheonix server and its working very smoothly. I can send message to the server channel. But I can’t maintain its continous connection with server.

Here’s my client phxsocket code:

import phxsocket
import ssl
# Create socket client
headers = {'Authorization': 'Basic YWRtaW46YWRtaW4='}
socket = phxsocket.Client("ws://localhost:4000/socket/websocket", {"data": "STRING 1"})

# Connect and join a channel
if socket.connect(): # blocking, raises exception on failure
  channel = socket.channel("room:lobby")
  print("SUCCESSFULLY CONNECTED")
  resp = channel.join() # also blocking, raises exception on failure

# Alternatively
def connect_to_channel(socket, origin = 'com.universal-devices.websockets.isy', subprotocols = ['ISYSUB'],extra_headers=headers):
  channel = socket.channel("room:lobby")
  resp = channel.join()
  
socket.on_open = connect_to_channel


# Reconnect on disconnection
socket.on_close = lambda socket: socket.connect()

#Subscribe to events
def do_something(payload):
  thing = payload["thing"]

channel.on("eventname", do_something)

message = ""

# # Push data and wait for a response
message = channel.push("message:add", {"message": "HELLO WORLD"})

# Leave a channel
channel.leave()

# Disconnect
socket.close()

Seeking Guidance!

I’m out of practice reading Python code, but the docs for phxsocket suggest you need to tell the library that you’re expecting a response and then wait for it:

message = channel.push("eventname", {"some": "data"}, reply=True)
response = message.wait_for_response() # blocking
1 Like

On the server side - Phoenix Socket expects heartbeat to be sent periodically if the connection is idle. If server does not receive a heartbeat then socket disconnects on the server side.

Check if library you are using is doing this…

2 Likes

Absolutely, When I tried to debug this error too as well. But couldn’t find a way:
When I make it to wait for response then I get error in my phxsocket client as this:

response = message.wait_for_response() # blocking
AttributeError: 'NoneType' object has no attribute 'wait_for_response'

However the server received the data.

You’re absolutely correct.
I’m just sending single time message to the server. Is there any way possible to keep connection alive. Any other way?

Look for an alternative library or implement heartbeat in the current library? Why reinvent wheel with a new solution…

channel.push returning None is what I’d expect if the call didn’t have reply=True in it