socket.recvfrom() & sendto()

Ulrich Berning berning at teuto.de
Mon May 7 17:39:15 EDT 2001


Ron Johnson wrote:

> The mis-understanding that I am having is that you can only bind
> one socket to a server:port.  Ergo, how do have multiple sockets
> open at the same time?
>
> >>> import socket, select
> >>>
> >>> sock1 = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
> >>> sock1.setsockopt(socket.SOL_SOCKET,  socket.SO_REUSEADDR, 1)
> >>> sock1.setblocking(0)
> >>> sock1.bind((socket.gethostname(), 50000))
> >>> sock1.listen(5)
> >>>
> >>> sock2 = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
> >>> sock2.setsockopt(socket.SOL_SOCKET,  socket.SO_REUSEADDR, 1)
> >>> sock2.setblocking(0)
> >>> sock2.bind((socket.gethostname(), 50000))
> Traceback (most recent call last):
>   File "<stdin>", line 1, in ?
> socket.error: (98, 'Address already in use')

Hi,

I think, you want to something like that:

import socket, select, os

# Create a connection socket, bind it and listen on it
connect_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
connect_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
connect_socket.bind((socket.gethostname(), 50000))
connect_socket.listen(5)

# Our server accepts connect requests forever
while 1:
    # The accept() call blocks until there is a connect request.
    # The call returns a new socket, that should be used for further
    # communication.
    work_socket, addr = connect_socket.accept()
    # Start a new process (or thread) for client server communications
    # or use select() to do this in the same process
    child_pid = os.fork()
    if not child_pid: # Child process
        # The child process should close the connect socket immediately
        connect_socket.close()
        # This functions should do the communication with the client
        client_worker_function(work_socket)
        # When all work is done, the child can die
        sys.exit()


The trick is the accept() system call, which returns a new socket that
should be used for the client server communication. The connect socket
can then listen on the defined port for the next connect request.

Hope this helps,

Ulli

-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-list/attachments/20010507/b8d679a2/attachment.html>


More information about the Python-list mailing list