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












5















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" : "edmund@gmail.com"})
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)









share|improve this question

























  • why do you not need a password parameter? I think you need to provide some context of the server, the problem seems to be more than just "requires a while loop"

    – bunbun
    Dec 4 '18 at 9:48











  • @bunbun Where do you see a password parameter? I only need an email parameter

    – Edmund
    Dec 5 '18 at 7:07











  • you are telling it to only wait for a max of 3 seconds before carrying on with the last line, change that to socketIO.wait() to wait for a response.

    – James Kent
    Dec 6 '18 at 13:17











  • Software_delay,block_wait,block_read never solve your problem ! Need read some header data/bytes (cos header include content-length) and wait_until **if last_byte are received**(otherwise already got corrupted data).

    – dsgdfg
    Dec 6 '18 at 14:39













  • @JamesKent socketIO.wait() has nothing to do with the data await, it only ensures the duration of the socket connection to the server

    – Edmund
    Dec 7 '18 at 9:20
















5















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" : "edmund@gmail.com"})
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)









share|improve this question

























  • why do you not need a password parameter? I think you need to provide some context of the server, the problem seems to be more than just "requires a while loop"

    – bunbun
    Dec 4 '18 at 9:48











  • @bunbun Where do you see a password parameter? I only need an email parameter

    – Edmund
    Dec 5 '18 at 7:07











  • you are telling it to only wait for a max of 3 seconds before carrying on with the last line, change that to socketIO.wait() to wait for a response.

    – James Kent
    Dec 6 '18 at 13:17











  • Software_delay,block_wait,block_read never solve your problem ! Need read some header data/bytes (cos header include content-length) and wait_until **if last_byte are received**(otherwise already got corrupted data).

    – dsgdfg
    Dec 6 '18 at 14:39













  • @JamesKent socketIO.wait() has nothing to do with the data await, it only ensures the duration of the socket connection to the server

    – Edmund
    Dec 7 '18 at 9:20














5












5








5


1






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" : "edmund@gmail.com"})
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)









share|improve this question
















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" : "edmund@gmail.com"})
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)






python sockets






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Dec 4 '18 at 3:51









bunbun

2,03532447




2,03532447










asked Nov 13 '18 at 16:40









EdmundEdmund

879




879













  • why do you not need a password parameter? I think you need to provide some context of the server, the problem seems to be more than just "requires a while loop"

    – bunbun
    Dec 4 '18 at 9:48











  • @bunbun Where do you see a password parameter? I only need an email parameter

    – Edmund
    Dec 5 '18 at 7:07











  • you are telling it to only wait for a max of 3 seconds before carrying on with the last line, change that to socketIO.wait() to wait for a response.

    – James Kent
    Dec 6 '18 at 13:17











  • Software_delay,block_wait,block_read never solve your problem ! Need read some header data/bytes (cos header include content-length) and wait_until **if last_byte are received**(otherwise already got corrupted data).

    – dsgdfg
    Dec 6 '18 at 14:39













  • @JamesKent socketIO.wait() has nothing to do with the data await, it only ensures the duration of the socket connection to the server

    – Edmund
    Dec 7 '18 at 9:20



















  • why do you not need a password parameter? I think you need to provide some context of the server, the problem seems to be more than just "requires a while loop"

    – bunbun
    Dec 4 '18 at 9:48











  • @bunbun Where do you see a password parameter? I only need an email parameter

    – Edmund
    Dec 5 '18 at 7:07











  • you are telling it to only wait for a max of 3 seconds before carrying on with the last line, change that to socketIO.wait() to wait for a response.

    – James Kent
    Dec 6 '18 at 13:17











  • Software_delay,block_wait,block_read never solve your problem ! Need read some header data/bytes (cos header include content-length) and wait_until **if last_byte are received**(otherwise already got corrupted data).

    – dsgdfg
    Dec 6 '18 at 14:39













  • @JamesKent socketIO.wait() has nothing to do with the data await, it only ensures the duration of the socket connection to the server

    – Edmund
    Dec 7 '18 at 9:20

















why do you not need a password parameter? I think you need to provide some context of the server, the problem seems to be more than just "requires a while loop"

– bunbun
Dec 4 '18 at 9:48





why do you not need a password parameter? I think you need to provide some context of the server, the problem seems to be more than just "requires a while loop"

– bunbun
Dec 4 '18 at 9:48













@bunbun Where do you see a password parameter? I only need an email parameter

– Edmund
Dec 5 '18 at 7:07





@bunbun Where do you see a password parameter? I only need an email parameter

– Edmund
Dec 5 '18 at 7:07













you are telling it to only wait for a max of 3 seconds before carrying on with the last line, change that to socketIO.wait() to wait for a response.

– James Kent
Dec 6 '18 at 13:17





you are telling it to only wait for a max of 3 seconds before carrying on with the last line, change that to socketIO.wait() to wait for a response.

– James Kent
Dec 6 '18 at 13:17













Software_delay,block_wait,block_read never solve your problem ! Need read some header data/bytes (cos header include content-length) and wait_until **if last_byte are received**(otherwise already got corrupted data).

– dsgdfg
Dec 6 '18 at 14:39







Software_delay,block_wait,block_read never solve your problem ! Need read some header data/bytes (cos header include content-length) and wait_until **if last_byte are received**(otherwise already got corrupted data).

– dsgdfg
Dec 6 '18 at 14:39















@JamesKent socketIO.wait() has nothing to do with the data await, it only ensures the duration of the socket connection to the server

– Edmund
Dec 7 '18 at 9:20





@JamesKent socketIO.wait() has nothing to do with the data await, it only ensures the duration of the socket connection to the server

– Edmund
Dec 7 '18 at 9:20












3 Answers
3






active

oldest

votes


















2





+25









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()





share|improve this answer


























  • How can I connect to the socket using email as a parameter? And after connecting, how can I emit to a socket parameter?

    – Edmund
    Dec 4 '18 at 9:02



















1














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()





share|improve this answer































    0














    Since you're using the SocketIO library to include parameters (achieved using requests), and want to emit a message, you can wait indefinitely for a response by not specifying a wait time.



    with SocketIO(host, params={"email" : "edmund@gmail.com"}) as socketIO:
    def on_response_state(*args):
    print args # Prints ()

    socketIO.emit('receive_state', on_response_state)
    socketIO.wait()





    share|improve this answer
























    • unfortunately, your solution does not work. It does not wait for a data, after emitting it goes straight to callback and then the indefinite wait comes

      – Edmund
      Dec 7 '18 at 9:20











    Your Answer






    StackExchange.ifUsing("editor", function () {
    StackExchange.using("externalEditor", function () {
    StackExchange.using("snippets", function () {
    StackExchange.snippets.init();
    });
    });
    }, "code-snippets");

    StackExchange.ready(function() {
    var channelOptions = {
    tags: "".split(" "),
    id: "1"
    };
    initTagRenderer("".split(" "), "".split(" "), channelOptions);

    StackExchange.using("externalEditor", function() {
    // Have to fire editor after snippets, if snippets enabled
    if (StackExchange.settings.snippets.snippetsEnabled) {
    StackExchange.using("snippets", function() {
    createEditor();
    });
    }
    else {
    createEditor();
    }
    });

    function createEditor() {
    StackExchange.prepareEditor({
    heartbeatType: 'answer',
    autoActivateHeartbeat: false,
    convertImagesToLinks: true,
    noModals: true,
    showLowRepImageUploadWarning: true,
    reputationToPostImages: 10,
    bindNavPrevention: true,
    postfix: "",
    imageUploader: {
    brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
    contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
    allowUrls: true
    },
    onDemand: true,
    discardSelector: ".discard-answer"
    ,immediatelyShowMarkdownHelp:true
    });


    }
    });














    draft saved

    draft discarded


















    StackExchange.ready(
    function () {
    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53285659%2fhow-can-i-wait-until-i-receive-data-using-a-python-socket%23new-answer', 'question_page');
    }
    );

    Post as a guest















    Required, but never shown

























    3 Answers
    3






    active

    oldest

    votes








    3 Answers
    3






    active

    oldest

    votes









    active

    oldest

    votes






    active

    oldest

    votes









    2





    +25









    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()





    share|improve this answer


























    • How can I connect to the socket using email as a parameter? And after connecting, how can I emit to a socket parameter?

      – Edmund
      Dec 4 '18 at 9:02
















    2





    +25









    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()





    share|improve this answer


























    • How can I connect to the socket using email as a parameter? And after connecting, how can I emit to a socket parameter?

      – Edmund
      Dec 4 '18 at 9:02














    2





    +25







    2





    +25



    2




    +25





    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()





    share|improve this answer















    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()






    share|improve this answer














    share|improve this answer



    share|improve this answer








    edited Dec 4 '18 at 2:01

























    answered Dec 4 '18 at 1:41









    bunbunbunbun

    2,03532447




    2,03532447













    • How can I connect to the socket using email as a parameter? And after connecting, how can I emit to a socket parameter?

      – Edmund
      Dec 4 '18 at 9:02



















    • How can I connect to the socket using email as a parameter? And after connecting, how can I emit to a socket parameter?

      – Edmund
      Dec 4 '18 at 9:02

















    How can I connect to the socket using email as a parameter? And after connecting, how can I emit to a socket parameter?

    – Edmund
    Dec 4 '18 at 9:02





    How can I connect to the socket using email as a parameter? And after connecting, how can I emit to a socket parameter?

    – Edmund
    Dec 4 '18 at 9:02













    1














    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()





    share|improve this answer




























      1














      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()





      share|improve this answer


























        1












        1








        1







        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()





        share|improve this answer













        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()






        share|improve this answer












        share|improve this answer



        share|improve this answer










        answered Dec 4 '18 at 1:19









        neoneo

        112




        112























            0














            Since you're using the SocketIO library to include parameters (achieved using requests), and want to emit a message, you can wait indefinitely for a response by not specifying a wait time.



            with SocketIO(host, params={"email" : "edmund@gmail.com"}) as socketIO:
            def on_response_state(*args):
            print args # Prints ()

            socketIO.emit('receive_state', on_response_state)
            socketIO.wait()





            share|improve this answer
























            • unfortunately, your solution does not work. It does not wait for a data, after emitting it goes straight to callback and then the indefinite wait comes

              – Edmund
              Dec 7 '18 at 9:20
















            0














            Since you're using the SocketIO library to include parameters (achieved using requests), and want to emit a message, you can wait indefinitely for a response by not specifying a wait time.



            with SocketIO(host, params={"email" : "edmund@gmail.com"}) as socketIO:
            def on_response_state(*args):
            print args # Prints ()

            socketIO.emit('receive_state', on_response_state)
            socketIO.wait()





            share|improve this answer
























            • unfortunately, your solution does not work. It does not wait for a data, after emitting it goes straight to callback and then the indefinite wait comes

              – Edmund
              Dec 7 '18 at 9:20














            0












            0








            0







            Since you're using the SocketIO library to include parameters (achieved using requests), and want to emit a message, you can wait indefinitely for a response by not specifying a wait time.



            with SocketIO(host, params={"email" : "edmund@gmail.com"}) as socketIO:
            def on_response_state(*args):
            print args # Prints ()

            socketIO.emit('receive_state', on_response_state)
            socketIO.wait()





            share|improve this answer













            Since you're using the SocketIO library to include parameters (achieved using requests), and want to emit a message, you can wait indefinitely for a response by not specifying a wait time.



            with SocketIO(host, params={"email" : "edmund@gmail.com"}) as socketIO:
            def on_response_state(*args):
            print args # Prints ()

            socketIO.emit('receive_state', on_response_state)
            socketIO.wait()






            share|improve this answer












            share|improve this answer



            share|improve this answer










            answered Dec 7 '18 at 1:12









            bunbunbunbun

            2,03532447




            2,03532447













            • unfortunately, your solution does not work. It does not wait for a data, after emitting it goes straight to callback and then the indefinite wait comes

              – Edmund
              Dec 7 '18 at 9:20



















            • unfortunately, your solution does not work. It does not wait for a data, after emitting it goes straight to callback and then the indefinite wait comes

              – Edmund
              Dec 7 '18 at 9:20

















            unfortunately, your solution does not work. It does not wait for a data, after emitting it goes straight to callback and then the indefinite wait comes

            – Edmund
            Dec 7 '18 at 9:20





            unfortunately, your solution does not work. It does not wait for a data, after emitting it goes straight to callback and then the indefinite wait comes

            – Edmund
            Dec 7 '18 at 9:20


















            draft saved

            draft discarded




















































            Thanks for contributing an answer to Stack Overflow!


            • Please be sure to answer the question. Provide details and share your research!

            But avoid



            • Asking for help, clarification, or responding to other answers.

            • Making statements based on opinion; back them up with references or personal experience.


            To learn more, see our tips on writing great answers.




            draft saved


            draft discarded














            StackExchange.ready(
            function () {
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53285659%2fhow-can-i-wait-until-i-receive-data-using-a-python-socket%23new-answer', 'question_page');
            }
            );

            Post as a guest















            Required, but never shown





















































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown

































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown







            Popular posts from this blog

            Full-time equivalent

            さくらももこ

            13 indicted, 8 arrested in Calif. drug cartel investigation