Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Failed to connect to remote sanic-websocket [Errno 111] Connection refused #3033

Open
1 task done
RomanPerekhrest opened this issue Feb 3, 2025 · 0 comments
Open
1 task done
Labels

Comments

@RomanPerekhrest
Copy link

RomanPerekhrest commented Feb 3, 2025

Is there an existing issue for this?

  • I have searched the existing issues

Describe the bug

Cannot connect to a remote sanic-websocket server endpoint (serves also several http endpoints).
Got constant error both

  • from CLI client:
$ python -m websockets ws://*.*.*.*:7000/feed/
Failed to connect to ws://*.*.*.*:7000/feed/: [Errno 111] Connection refused.
  • and from python script:
connect failed; reconnecting in 1.8 seconds: asyncio.exceptions.TimeoutError: timed out during handshake
{'time':'2025-02-03 20:53:31,161', 'level': 'INFO', 'message': connect failed; reconnecting in 1.8 seconds: asyncio.exceptions.TimeoutError: timed out during handshake}
connect failed; reconnecting in 3.1 seconds: asyncio.exceptions.TimeoutError: timed out during handshake
{'time':'2025-02-03 20:53:43,025', 'level': 'INFO', 'message': connect failed; reconnecting in 3.1 seconds: asyncio.exceptions.TimeoutError: timed out during handshake}
connect failed; reconnecting in 5.0 seconds: asyncio.exceptions.TimeoutError: timed out during handshake
...

*IP is masked for abstraction.

Code snippet

# Client
import asyncio

from websockets.asyncio.client import connect
from websockets.exceptions import ConnectionClosed

WS_URI = "ws://*.*.*.*:7000/feed/"

...
async def connect(self):
    # reconnect when the connection drops
    async for ws in connect(WS_URI):
        self._ws = ws       
        try:
            await ws.wait_closed()
        finally:
            # logger.error(f"Connection is closed.")
            self._ws = None
...
----------
# Remote sanic-websocket endpoint
from sanic import Blueprint
from sanic import Sanic, Websocket, Request
from websockets.exceptions import ConnectionClosed, WebSocketException
from websockets import broadcast
from sanic.log import websockets_logger

import asyncio

app = Sanic.get_app()
ws_bp = Blueprint("ws_bp")

async def send_one(ws: Websocket, msg: str | bytes):
    """Send message to the specified websocket client"""
    try:
        await ws.send(msg)
    except ConnectionClosed:
        pass


def submit_broadcast(ws_clients, msg):
    """Submit background tasks for broadcast event"""
    for client in ws_clients:
        asyncio.create_task(send_one(client, msg))

@ws_bp.websocket("/feed/", name="feeder")
async def feed(request: Request, ws: Websocket):
    """Feeder"""
   
    app_ctx = request.app.ctx
  
    try:
        async for message in ws:            
            app_ctx.data["msg"] = message
            try:
                if app_ctx.wsclients:
                    submit_broadcast(app_ctx.wsclients, message)
                    await asyncio.sleep(0)
            except Exception as ex:
                websockets_logger.error(f"Failed to broadcast message. {ex}")
    except ConnectionClosed as ex:
        websockets_logger.warning(ex)
...

# Running lines:
if __name__ == "__main__":
    app.run(port=7000, access_log=False, debug=True, auto_reload=True)

Expected Behavior

websocket connection is established and able for data exchange

How do you run Sanic?

As a script (app.run or Sanic.serve)

Operating System

Linux

Sanic Version

24.12.0

Additional context

I also had to switch to websockets 14.1 due to the issue #3031 ("websocket Unrecognized frame opcode: 13")

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

1 participant