0

Before using socketserver and TCP, my chat client would listen like this:

def recvData(self):
    try:
        while True:
            data = self.sock.recv(1024)
            if data:
                data_handler(data)
    except:
        pass

while running:
    dt = clock.tick(60)
    client.recvData()

How do you emulate this behavior for a client when its server is using a TCP socketserver?

EDIT here is my (poor) attempt:

    def recvData(self):
        recvsock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        recvsock.connect(("192.168.0.7", 1234))
        recvsock.setblocking(0)
        while True:
            data = recvsock.recv(1024)
            if data:
                print(data)
                data_handler(data)

I'm getting:

BlockingIOError: [WinError 10035] A non-blocking socket operation could not be completed immediately
  • Do you really want a non-blocking socket? – DaveBensonPhillips Apr 04 '16 at 16:27
  • I believe so, since I may be receiving something whilst doing something else... or am I misunderstanding socket blocking? – Dysprosium Dysprosium Apr 04 '16 at 16:39
  • No, that sounds like you have the right understanding, except that you're trying to make a blocking call (`recvsock.recv`) and not handling the exception thrown. You could look into using either the `select` or `asyncio` module to achieve what you need. – DaveBensonPhillips Apr 04 '16 at 16:46
  • @HumphreyTriscuit I have now an "except: pass" because I obviously can't guarantee getting a piece of data every single time I try it... but I'm still getting the same error.... – Dysprosium Dysprosium Apr 04 '16 at 16:58
  • See http://stackoverflow.com/questions/11647046/non-blocking-socket-error-is-always for an implementation using try/except, although I think that approach is a bit naive. `select`/`asyncio` would be more helpful here – DaveBensonPhillips Apr 04 '16 at 17:44

0 Answers0