socket.accept()无效参数

时间:2017-09-21 13:33:37

标签: python sockets server

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

#Some Error in sock.accept (line 13) --> no fix yet
import socket
import sys

serversocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
host = socket.gethostname()

print >>sys.stderr, 'starting up on %s' % host
serversocket.bind((host, 9999))
serversocket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)

#listening for incoming connections
while True:
    # Wait for a connection
    print >>sys.stderr, 'waiting for a connection'
    connection , client_address = serversocket.accept()
    try:
        print >>sys.stderr, 'connection from', client_address
        #Receive data in small chunks and retransmit it
        while True:
            data = connection.recv(16)
            print >>sys.stderr,'received "%s"' % data
            if data:
                print >>sys.stderr, 'sending data back to the client'
                connection.sendall(data)
            else:
                print >>sys.stderr, 'no more data from', client_address
                break
    finally:
        #Clean up the connection
        #Will be executed everytime
        connection.close()

它给出的输出是

C:\Python27\python27.exe C:/Users/Marcel/Desktop/Projekte/Python/Sockets/Socket_Test/server.py
starting up on Marcel-HP
waiting for a connection
Traceback (most recent call last):
  File "C:/Users/Marcel/Desktop/Projekte/Python/Sockets/Socket_Test/server.py", line 16, in <module>
    connection , client_address = serversocket.accept()
  File "C:\Python27\lib\socket.py", line 206, in accept
    sock, addr = self._sock.accept()
socket.error: [Errno 10022] Ein ung�ltiges Argument wurde angegeben

1 个答案:

答案 0 :(得分:1)

在接受任何连接之前,您应该开始[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()

因此,在您的情况下,您只能在serversocket.listen(1)

之后错过serversocket.setsockopt(...)