socket.accept() 无效参数

MNC*_*ODE 3 python sockets server

我试图使用模块套接字创建一个简单的客户端/服务器程序。这是每个标准套接字实现的基本教程。

\n\n
#Some Error in sock.accept (line 13) --> no fix yet\nimport socket\nimport sys\n\nserversocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\nhost = socket.gethostname()\n\nprint >>sys.stderr, \'starting up on %s\' % host\nserversocket.bind((host, 9999))\nserversocket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)\n\n#listening for incoming connections\nwhile True:\n    # Wait for a connection\n    print >>sys.stderr, \'waiting for a connection\'\n    connection , client_address = serversocket.accept()\n    try:\n        print >>sys.stderr, \'connection from\', client_address\n        #Receive data in small chunks and retransmit it\n        while True:\n            data = connection.recv(16)\n            print >>sys.stderr,\'received "%s"\' % data\n            if data:\n                print >>sys.stderr, \'sending data back to the client\'\n                connection.sendall(data)\n            else:\n                print >>sys.stderr, \'no more data from\', client_address\n                break\n    finally:\n        #Clean up the connection\n        #Will be executed everytime\n        connection.close()\n
Run Code Online (Sandbox Code Playgroud)\n\n

它给出的输出是

\n\n
C:\\Python27\\python27.exe C:/Users/Marcel/Desktop/Projekte/Python/Sockets/Socket_Test/server.py\nstarting up on Marcel-HP\nwaiting for a connection\nTraceback (most recent call last):\n  File "C:/Users/Marcel/Desktop/Projekte/Python/Sockets/Socket_Test/server.py", line 16, in <module>\n    connection , client_address = serversocket.accept()\n  File "C:\\Python27\\lib\\socket.py", line 206, in accept\n    sock, addr = self._sock.accept()\nsocket.error: [Errno 10022] Ein ung\xef\xbf\xbdltiges Argument wurde angegeben\n
Run Code Online (Sandbox Code Playgroud)\n

Céd*_*ien 5

在接受任何连接之前,您应该开始[listen()][1]建立新的连接。这是 python 文档中的基本示例:

import socket

HOST = ''                 # Symbolic name meaning all available interfaces
PORT = 50007              # Arbitrary non-privileged port
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)  # Creation of the socket
s.bind((HOST, PORT))      # We tell OS on which address/port we will listen
s.listen(1)               # We ask OS to start listening on this port, with the number of pending/waiting connection you'll allow 
conn, addr = s.accept()   # Then, accept a new connection
print 'Connected by', addr
while 1:
    data = conn.recv(1024)
    if not data: break
    conn.sendall(data)
conn.close()
Run Code Online (Sandbox Code Playgroud)

因此,就您而言,您只会错过serversocket.listen(1)或之后的右侧serversocket.setsockopt(...)