Skip to content

Python server not responsive #1320

@ferrydjaja

Description

@ferrydjaja

I have the python server like this and NodeJS client. The client can connect to the server, but when emit the message to server, the server didn't get the immediate response. It will take a while for server to receive the message.
Here is my code:

Python server:

from aiohttp import web
import socketio

# creates a new Async Socket IO Server
sio = socketio.AsyncServer(async_mode='aiohttp')
# Creates a new Aiohttp Web Application
app = web.Application()
# Binds our Socket.IO server to our Web App
# instance
sio.attach(app)

# we can define aiohttp endpoints just as we normally
# would with no change
async def index(request):
    with open('index.html') as f:
        return web.Response(text=f.read(), content_type='text/html')

# If we wanted to create a new websocket endpoint,
# use this decorator, passing in the name of the
# event we wish to listen out for
@sio.on('message')
async def print_message(sid, message):
    # When we receive a new event of type
    # 'message' through a socket.io connection
    # we print the socket ID and the message
    print("Socket ID: " , sid)
    print(message)
	# await a successful emit of our reversed message
    # back to the client
    await sio.emit('message', message.get("number", "none"))

# We bind our aiohttp endpoint to our app
# router
app.router.add_get('/', index)

# We kick off our server
if __name__ == '__main__':
    web.run_app(app)

NodeJS client:

const io = require('socket.io-client');

const socket = io('http://localhost:8080');

socket.on('message', data => {
  console.log("data:"+data);
  if(data === 2) {
	console.log('Got from server: ');
	console.log(data);
  }
});

function generateNumber() {
  //const n = Math.floor(Math.random() * 50);
  return { number: 2 };
}

function sendMsg() {
  const json = generateNumber();
  console.log('Sending to server:');
  console.log(json);

  socket.emit('message', 'HELLO WORLD');
}

function loop() {
  const rand = Math.round(Math.random() * (3000 - 500)) + 500;
  console.log(`Setting timeout ${rand}ms`);
  setTimeout(() => {
    sendMsg();
    loop();
  }, 10 * 1000);
}

socket.on('connect', () => {
  console.log('Connected to server');
  loop();
});

Here is the log from client:

Connected to server
Setting timeout 2080ms
Sending to server:
{ number: 2 }
Setting timeout 1608ms
Sending to server:
{ number: 2 }
Setting timeout 2740ms

As you can see it didn't get the message back from server after sending it.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions