2017-09-21 35 views
2

我試圖用模塊套接字創建一個簡單的客戶端/服務器程序。它是每個標準套接字實現的基本教程。socket.accept()無效的參數

#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

接受任何連接之前,你應該開始[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(...)

之後