python - 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() 行之前睡觉,但这没有奏效。
解决方案
您正在调用accept
未通过调用设置为被动模式的客户端套接字上的方法listen
。此外,套接字已经处于连接状态(connect
之前调用过),现在你不能指望你的套接字监听和接受连接。但长话短说,只需删除您accept
在客户端调用的代码,它就可以正常运行。
推荐阅读
- angular - 在通过 http 加载的 typescript 对象上使用 mat-form-field 输入的 2 向数据绑定
- react-native - 如何用玩笑测试组件的功能?
- android - 如何在 Kotlin 中使用 ViewModel 测试协程?
- excel - Excel宏或函数:如果单元格不为空,则使用循环值(来自另一张表)填充单元格范围(A列)
- javascript - 异步函数和 promise 需要很长时间才能解决
- javascript - 如何通过 normalizrjs 规范化 javascript 中的数据?
- grafana - 如果使用 iframe,如何更改 Grafana 的时间范围?
- typescript - 如何在 Typescript 中根据变量设置动态类型
- image-processing - 使用 libvips 重新缩放图像
- javascript - CS50 Finance 中的用户名检查问题