首页 > 解决方案 > Python OSError:[WinError 10022] 提供了无效参数 | fd, addr = self._accept()

问题描述

我正在尝试用 Python 制作一个简单的客户端和服务器。服务器似乎完全没问题,但客户端抛出以下错误:

  File "C:\Users\me\Desktop\Client.py", line 6, in <module>
    connection, address = client.accept()
  File "C:\Users\me\AppData\Local\Programs\Python\Python38-32\lib\socket.py", line 292, in accept
    fd, addr = self._accept()
OSError: [WinError 10022] An invalid argument was supplied

这是服务器代码:

server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server.bind((socket.gethostname(), 8080))
server.listen(5)

while True:
    connection, address = server.accept()
    fromClient = ''

    while True:
        data = connection.recv(2048)
        if not data:
            break
        fromClient = fromClient + data
        print(fromClient)
        connection.send(str.encode('yo'))
    connection.close()
    print('client disconnected')

这是客户端代码:

import time
client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
client.connect((socket.gethostname(), 8080))
client.settimeout(3)
time.sleep(3)
#client.send(str.encode('client'))
connection, address = client.accept()
fromServer = client.recv(2048)
fromServer = fromServer.decode('utf-8')
client.close()
print(fromServer)

服务器绑定到 ip 和端口,所以它们没问题,但是客户端在尝试相同的事情时出错。我能做些什么来解决这个问题吗?

我也试过在 client.accept() 行之前睡觉,但这没有奏效。

标签: pythonwindowssocketsserverclient

解决方案


您正在调用accept未通过调用设置为被动模式的客户端套接字上的方法listen。此外,套接字已经处于连接状态(connect之前调用过),现在你不能指望你的套接字监听和接受连接。但长话短说,只需删除您accept在客户端调用的代码,它就可以正常运行。


推荐阅读