简体   繁体   中英

How to receive Socket.IO socket using native socket module in Python

When I am trying to receive a message from Socket.IO using the native socket module, instead of receiving the message, I receive this:

GET /socket.io/?EIO=3&transport=polling&t=MIlsTQ_ HTTP/1.1

Host: localhost:5000

Connection: keep-alive

Accept: */*

Origin: http://localhost:8080

User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/67.0.3396.99 Safari/537.36

DNT: 1

Referer: http://localhost:8080/

Accept-Encoding: gzip, deflate, br

Accept-Language: en-US,en;q=0.9

How do I fix this, and receive the message rather than the data?

Client code:

  socketsSend: function() {
  const socket = io.connect('http://localhost:5000');
  /*var socket = io.Socket('http://localhost', {
    port: 5000
  });*/
  socket.connect();
  socket._connectTimer = setTimeout(function() {
   socket.close();
  }, 500);

    socket.on('connect', function() {
// socket connected successfully, clear the timer
    clearTimeout(socket._connectTimer);
});

Server code:

import socket
import json
addr = 'localhost',5000
sock=socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.bind(addr)
sock.listen(3)
while True:
    connection, client_address = sock.accept()
    data = connection.recv(100000)
    print(data.decode('utf-8'))

From this how to guide:

In general, they [socket's recv and send functions] return when the associated network buffers have been filled (send) or emptied (recv). They then tell you how many bytes they handled. It is your responsibility to call them again until your message has been completely dealt with.

So, from my understanding, connection.recv(100000) won't return any data until its buffer fills up, so to fix this you would need to set buffer to something low, (maybe 2048?).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM