Why does the Connection close after the message has been sent?

test29998411 281 Reputation points
2023-12-28T07:09:48.3933333+00:00

I have written code in Python to send a response to the client after receiving a message.

But I get the following error.

import asyncio
import sys
import websockets

from azure.messaging.webpubsubservice import WebPubSubServiceClient


async def connect(url):
    async with websockets.connect(url) as ws:
        print('connected')
        while True:
            print('Message received: ' + await ws.recv())
            await ws.send('Response OK')
if __name__ == '__main__':

    if len(sys.argv) != 3:
        print('Usage: python subscribe.py <connection-string> <hub-name>')
        exit(1)

    connection_string = sys.argv[1]
    hub_name = sys.argv[2]

    service = WebPubSubServiceClient.from_connection_string(connection_string, hub=hub_name)
    token = service.get_client_access_token()

    try:
        asyncio.get_event_loop().run_until_complete(connect(token['url']))
    except KeyboardInterrupt:
        pass

Why does the Connection close after the message has been sent?


print('Message received: ' + await ws.recv())  
File "websockets\legacy\protocol.py", line 568, in recv  
await self.ensure_open()  
File "websockets\legacy\protocol.py", line 948, in ensure_open  
raise self.connection_closed_exc()  
websockets.exceptions.ConnectionClosedOK: received 1000 (OK); then sent 1000 (OK)  
Azure Web PubSub
Azure Web PubSub
An Azure service that provides real-time messaging for web applications using WebSockets and the publish-subscribe pattern.
60 questions
0 comments No comments
{count} votes

2 answers

Sort by: Most helpful
  1. brtrach-MSFT 15,256 Reputation points Microsoft Employee
    2023-12-30T05:00:42.2666667+00:00

    @test29998411 The reason you are getting the ConnectionClosedOK error is that the WebSocket connection is being closed after the message is sent. This is because the async with statement in the connect function creates a context in which the WebSocket connection is open, and when the context is exited (i.e., when the async with block is exited), the connection is closed.

    To keep the connection open, you can modify the connect function to use a while loop that waits for messages and sends responses indefinitely. Here's an example:

    async def connect(url):
        async with websockets.connect(url) as ws:
            print('connected')
            while True:
                message = await ws.recv()
                print('Message received: ' + message)
                response = 'Response OK'
                await ws.send(response)
    

    This modified connect function will wait for messages indefinitely and send a response for each message it receives.


  2. brtrach-MSFT 15,256 Reputation points Microsoft Employee
    2024-01-02T23:56:03.4133333+00:00

    @test29998411 It seems like the issue persists even after modifying the connect function. The error message websockets.exceptions.ConnectionClosedOK: received 1000 (OK); then sent 1000 (OK) indicates that the WebSocket connection was closed normally, but it’s unclear why it’s closing immediately after sending a message.

    One possibility could be that the server is closing the connection. Some servers are configured to close the connection immediately after sending a response, especially if they are not designed to handle long-lived connections.

    Another possibility could be an issue with the WebPubSubServiceClient. If it’s not handling the WebSocket connection correctly, it might be closing the connection prematurely.

    Here are a few things you could try:

    1. Check the server’s configuration: Ensure that the server is configured to handle long-lived WebSocket connections.
    2. Handle connection closure in your code: You can add error handling in your code to manage the situation when the server closes the connection. Here’s an example:
    async def connect(url):
        async with websockets.connect(url) as ws:
            print('connected')
            while True:
                try:
                    message = await ws.recv()
                    print('Message received: ' + message)
                    response = 'Response OK'
                    await ws.send(response)
                except websockets.exceptions.ConnectionClosedOK:
                    print('Connection closed by the server')
                    break
    
    1. Debug the WebPubSubServiceClient: If you have access to the source code or documentation of WebPubSubServiceClient, check how it’s handling the WebSocket connections.

    Remember, it’s important to ensure that both the client and server are correctly configured to manage WebSocket connections. If the issue persists, you might want to reach out to the Azure Web PubSub team or the community for more specific guidance.

    0 comments No comments