2017-09-21 29 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]に開始する必要があります。

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.setsockopt(...)

serversocket.listen(1)を欠場: はここにPythonドキュメントからの基本的な例であります