0

我一直在尝试为一些简单的网络建立基础,并且一直遇到 WinError 10022 的问题。这是我的课程:

class SocketFactory:

    def __init__(self, secret):
        self.secret = secret

    def send(self, port, e_type, h_type, msg, ip="127.0.0.1"):

        s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
        print("Socket object successfully created.\n")

        s.bind((ip, port))
        print("Socket bound to port \n")

        while True:
            c, addr = s.accept()
            print('Connection established with ', addr)

            if h_type == 1:
                header = self.secret
                c.send(header, "utf-8")

            else:
                print("Incorrect header type. Exiting...\n")
                exit()

            if e_type == 1:
                c.send(bytes(msg, "utf-8"))

            else:
                print("Incorrect encoder type. Exiting...\n")
                exit()
        c.close()

初步的驱动程序代码是这样的:

from sockfactory import SocketFactory

print("Initializing masterserver setup...\n")

port = int(input("Enter port number: \n"))
#ip = str(input("Enter IPv4 address: \n"))
e_type = int(input("The encoding table for outbound bytes will be: \n" "1 = UTF-8 \n"))
h_type = int(input("The immutable header packet type will be: \n" "1 = Simple \n"))
msg = str(input("Enter packet payload: \n"))
secret = b'10000000011000101011110'

SocketFactory.send(port, e_type, h_type, msg, "127.0.0.1")

和错误信息:

    Traceback (most recent call last):
  File "C:/Users/EvESpirit/PycharmProjects/aaa/main", line 13, in <module>
    SocketFactory.send(port, e_type, h_type, msg, "127.0.0.1")
  File "C:\Users\EvESpirit\PycharmProjects\aaa\sockfactory.py", line 19, in send
    self.c, self.addr = s.accept()
  File "C:\Users\EvESpirit\AppData\Local\Programs\Python\Python38\lib\socket.py", line 292, in accept
    fd, addr = self._accept()
OSError: [WinError 10022] An invalid argument was supplied

有人能帮我一下吗?我做错了什么,我怎样才能做得更好?谢谢你。

4

1 回答 1

2

您在ands.listen()之间缺少:s.bind()s.accept()

>>> from socket import *
>>> s=socket()
>>> s.bind(('',5000))
>>> s.accept()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "C:\Python36\lib\socket.py", line 205, in accept
    fd, addr = self._accept()
OSError: [WinError 10022] An invalid argument was supplied
>>> s.listen()
>>> s.accept()  # waits here for a connection
于 2020-03-26T23:02:13.870 回答