goetzmoritz
goetzmoritz

Reputation: 453

"Parallel" Sockets in python

this is my UDP-Server very according to the UDP-Server-Example from the python-wiki:

# ----- receiver.py -----

#!/usr/bin/env python

from socket import *
import sys
import select

host="192.168.88.51"
port = 1337
s = socket(AF_INET,SOCK_DGRAM)
s.bind((host,port))

addr = (host,port)
buf=128

data,addr = s.recvfrom(buf)
print "Received File:"
f = open("out.jpg",'wb')

data, addr = s.recvfrom(buf)
try:
    while(data):
        f.write(data)
        s.settimeout(1)
        data,addr = s.recvfrom(buf)
except timeout:
    f.close()
    s.close()
    print "File Downloaded"

This code works fine and I'm able to receive ONE file at a time. But I have multiple clients and I'd like to receive every file coming in, so every time a new connection is established (from one certain IP). Any suggestions?

Upvotes: 0

Views: 2694

Answers (1)

Sam Chats
Sam Chats

Reputation: 2321

First of all, if you want an asynchronous server, it's better to not write things from scratch with sockets. Instead, use packages like asyncio or Twisted.

Coming to your problem, it's more convenient to go with a TCP-focused socket, therefore you should use SOCK_STREAM instead of the UDP type SOCK_DGRAM.

First, define a function for downloading:

def get_file(s):
    s.settimeout(1)
    with open("out.jpg",'wb') as f:
        data, addr = s.recv(buf)
        try:
            while(data):
                f.write(data)
                data, addr = s.recv(buf)
        except timeout:
            print "File Downloaded"

After setting up the constants (hostname, port number and so on), do something like the following (and do from threading import Thread first!):

s = socket(AF_INET,SOCK_DGRAM)
s.bind((host,port))
while True:
    print "Waiting for connection..."
    data, addr = s.recvfrom(buf)
    print "... connection from:", addr
    Thread(target=get_file, args=(s,)).start()  #starts a new thread for file download, addr acts like a filename

Upvotes: 1

Related Questions