Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I wait until I receive data using a Python socket?

Tags:

python

sockets

I am creating a socket client and trying to obtain some data. In order to do so, I need to connect to a web server via socket and the server actually creates another socket which listens and awaits for the data after which sends back to the client.

The problem I have with the code below is that my socket client does not wait for the incoming data from the server and just accepts empty data.

How can I wait for a non-empty data from the server using Python sockets?

My code:

import sys
import json
import socketIO_client
import time

host = 'https://SOME_URL'

socketIO = socketIO_client.SocketIO(host, params={"email" : "[email protected]"})
def on_connect(*args):
    print "socket.io connected"

def on_disconnect(*args):
    print "socketIO diconnected"

socketIO.on('connect', on_connect)
socketIO.on('disconnect', on_disconnect)

def on_response_state(*args):
    print args # Prints ()

socketIO.emit('receive_state',on_response_state)
socketIO.wait_for_callbacks(seconds=3)
like image 869
aikhs Avatar asked Nov 13 '18 16:11

aikhs


2 Answers

Here's an example using socket. Using s.accept(), the client will wait till a client accepts the connection before starting the while loop to receive data. This should help with your problem.

def receiver():
    PORT = 123
    CHUNK_SIZE = 1024

    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
    s.bind(('0.0.0.0', PORT))
    s.listen(1)
    conn,address=s.accept()  # accept an incoming connection using accept() method which will block until a new client connects

    while True:
        datachunk = conn.recv(CHUNK_SIZE) # reads data chunk from the socket in batches using method recv() until it returns an empty string
        if not datachunk:
            break  # no more data coming in, so break out of the while loop
        data.append(datachunk)  # add chunk to your already collected data

    conn.close()
    print(data)
    return

receiver()
like image 115
bunbun Avatar answered Nov 01 '22 14:11

bunbun


put the recv socket in a while thread.

like this:

  def rec(self):

    while 1:
        sleep 0.01
        rdata = self.clientsocket.recv(self.buffsize)

        print("rec from server: ", rdata.decode('utf8'),'\n','press enter to continue')

....

t2 = threading.Thread(target=y.rec, name="rec") 

t2.start()
like image 1
neo Avatar answered Nov 01 '22 15:11

neo