0

有一个服务器进程在我的机器上监听 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
<<<
4

1 回答 1

0

Windows 套接字的问题在于,除非您告诉它们,否则当您关闭它们时它们实际上并没有死。初始化套接字后尝试添加以下代码,看看会发生什么。

l_onoff = 1
l_linger = 0
s.setsockopt(socket.SOL_SOCKET, socket.SO_LINGER, 
                 struct.pack('ii', l_onoff, l_linger))

Lingering的文档可以在 MSDN 上找到。

还将您的关机更改为:

s.shutdown(socket.SHUT_RDWR)

如果 Windows 自己运行,这应该立即关闭所有连接。这将防止由于过多的套接字挥之不去而导致的缓冲区错误。

于 2013-09-12T13:36:54.287 回答