有一个服务器进程在我的机器上侦听端口8000.并且,客户端进程正在尝试连续地与服务器通信。每次打开新的套接字连接并因某种原因关闭连接。这是一个持续的过程。但是,当我尝试使用粘贴代码时,我无法在一定限制后创建套接字连接。在我的Windows机器中,它在创建/关闭16k连接后抛出错误。
运行此处给出的示例代码时出现10055错误。 “连接失败。错误代码:10055消息无法执行套接字上的操作,因为系统缺少足够的缓冲区空间或因为队列已满”
import socket
import sys
from time import sleep
HOST = socket.gethostbyname(socket.gethostname())
PORT = 8000
open = 0
close = 0
def connect(host, port, message=None):
global open
global close
open += 1
s = socket.socket()
# s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
print 'Socket created'
try:
s.connect((host, port))
except socket.error , msg:
print "open count=%s" % open
print "close count=%s" % close
print 'Connect failed. Error Code : ' + str(msg[0]) + ' Message ' + msg[1]
sys.exit()
print "Sending a msg"
s.sendall('Hello\n') #send only takes string
count = 1
while True:
data = s.recv(1024)
print "RECE data:<%s>" % data
if not data and count < 5:
print "Wait for data..."
count += 1
else:
break
s.shutdown(1)
s.close()
del s
close += 1
print 'Socket connect complete for %s:%s' % (host, port)
while 1:
print 'Connected with ', HOST
connect(HOST, 8000)
print "Wait for 1 sec"
sleep(1)
output like this:
>>>
:
:
Wait for 1 sec
Connected with <server-ip>
Socket created
Sending a msg
RECE data:<Got your msg: <Hello>
>
Socket connect complete for <server-ip:port>
Wait for 1 sec
Socket created <server-ip>
### open count=16338
### close count=16337
Connect failed. Error Code : 10055 Message An operation on a socket could not be performed because the system lacked sufficient buffer space or because a queue was full
<<<
答案 0 :(得分:0)
Windows套接字的问题在于,当你关闭它们时它们实际上不会死掉,除非你告诉它们。初始化套接字后尝试添加以下代码,看看会发生什么。
l_onoff = 1
l_linger = 0
s.setsockopt(socket.SOL_SOCKET, socket.SO_LINGER,
struct.pack('ii', l_onoff, l_linger))
可以在MSDN上找到Lingering的文档。
也将关机更改为:
s.shutdown(socket.SHUT_RDWR)
如果Windows自身行为,这应立即关闭所有连接。这样可以防止因插座过多导致的缓冲区错误。