socket.accept() invalid argument

Viewed 5600

I was trying to create an easy client/server program with the module socket. it is the basic tutorial for every standard socket implementation.

#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()

The output it gives is

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 Answers

Before accepting any connections, you should start to [listen()][1] to new connections. Here is the basic example from python documentation :

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

So, in your case, you only miss a serversocket.listen(1)right after the or serversocket.setsockopt(...)

Related