简体   繁体   中英

How can python socket client receive without being blocked

A simple demo of socket programming in python:

server.py

import socket

host = '127.0.0.1'
port = 8000

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind((host, port))
s.listen(1)

conn, addr = s.accept()

while True:
    data = conn.recv(1024)
    print 'Received:', data
    if not data:
        break
    conn.sendall(data)
    print 'Sent:', data

conn.close()

client.py

import socket

host = '127.0.0.1'
port = 8000

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

s.connect((host, port))
s.sendall('Hel')
s.sendall('lo world!')
print 'Received:', s.recv(1024)

s.close()

Now code work well. However, the client may not know if server will always send back every time. I tried symmetric code of while-loop in server.py

client_2.py

import socket

host = '127.0.0.1'
port = 8000

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

s.connect((host, port))
s.sendall('Hel')
s.sendall('lo world!')
while True:
    data = s.recv(1024)
    if not data:
        break
print 'Received:', data

s.close()

This code will block at

data = s.recv(1024)

But in server.py, if no data received, it will be blank string, and break from while-loop

Why it does not work for client? How can I do for same functionality without using timeout?

You can set a socket to non-blocking operation via socket.setblocking(false) , which is equivalent to socket.settimeout(0) . Solving this "without using timeout" is impossible.

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