python socket.recv() 一直不停的返回空字符串原因。
我遇到的是,因为客户端异常断开连接,之后服务端就一直接收到空字符串。
这样会无法分辨是客户端真的发了一个空串还是怎么样。
下面是复现问题的demo。
先运行server端:
# coding=utf-8
import socket
if __name__ == '__main__':
host = 'localhost'
port = 8765
server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server.bind((host, port))
server.listen(1) # 连接数
client, address = server.accept()
while True: # 循环收发数据包
data = client.recv(1024)
print ("data:"+data)
再运行client端:
# coding=utf-8
import socket
import time
if __name__ == '__main__':
host = 'localhost'
port = 8765
client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
client.setsockopt(socket.SOL_SOCKET, socket.SO_KEEPALIVE, 1) # 在客户端开启心跳维护
while True:
client.connect((host, port)) # ###注意这里,会报错导致代码崩溃,这时候去看服务端输出,就可以看到无限就收空串
client.send('hello world\r\n'.encode())
print('send data')
最终运行结果:
客户端结果:
send data
Traceback (most recent call last):
File "C:/Users/Rorschach/Desktop/test/test2.py", line 17, in
client.connect((host, port)) # ###注意这里,会报错导致代码崩溃,这时候去看服务端输出,就可以看到无限就收空串
File "C:\Python27\Lib\socket.py", line 228, in meth
return getattr(self._sock,name)(*args)
socket.error: [Errno 10056] A connect request was made on an already connected socket
服务端结果:
C:\Users\Rorschach\PycharmProjects\untitled\venv\Scripts\python.exe C:/Users/Rorschach/Desktop/test/test1.py
data:hello world
hello world
data:
data:
data:
data:
data:
data:
data:
data:
data:
data:
data:
data:
data:
data:
data:
data:
data:
data:
data:
data:
data:
data:
data:
data:
data:
data:
data:
data:
data:
data:
data:
data:
data:
data:
data:
data:
参考:https://blog.csdn.net/bbg221/article/details/78464051
侵删