这是我的服务器应用程序:
import socket, sys
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
sock.bind(("127.0.0.1", 1060))
sock.listen(1)
print("Server is ready to receive.")
s, sockname = sock.accept()
while True:
data = s.recv(100)
# dead lock happens without following 'if'
#if not data:
#break
print("The client from {} said: {}".format(s.getpeername(),
data.decode("utf-8")))
sys.stdout.flush()
这是客户:
import socket
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.connect(("127.0.0.1", 1060))
print("client is ready")
message = '''Hello, server, my name is client!
Here is oversize message: saasdasdas
asdasdasdasssasdasdasdasdasdacsdvas
sdavsdvavsdavxcvxczvdsavsavadsvasdv
xcavdasvdsavewavwvdsvdsavasdvdsavad
sdavsvxcvdavawevsdavsdavsavwevsdvsa
dsvasdvadsvdasvsdavsadvasdvsdavsdvv
sacascascwdqdadqwdqwdqwdsadwqdqwdqw
'''
data = message.encode("utf-8")
sock.sendall(data)
print("I have sent a message of {} length, now I want to close the
sock!".format(len(data)))
sock.close()
消息的长度(391bytes)比服务器套接字接收缓冲区(100字节)长。
如果我不添加:
if not data:
break
当客户端向服务器发送数据时,服务器的输出为:
The client from ('127.0.0.1', 63758) said:
The client from ('127.0.0.1', 63758) said:
The client from ('127.0.0.1', 63758) said:
The client from ('127.0.0.1', 63758) said:
The client from ('127.0.0.1', 63758) said:
(...dead loop...)
这里的方法recv()
是阻塞的,它可以从套接字缓冲区接收100个字节。
在我看来,服务器将收到4次,直到数据为止
发送完毕后,当所有数据都已发出时,服务器应用将在data = s.recv(100)
被阻止并等待下一个数据。
但事实并非如此。而且我也感到困惑的是,现在它似乎是非阻塞recv()
,为什么不打印data.decode("utf-8")
?