2

I'm trying to make a multi threading udp server with python.

Here is what I am doing :

#!/usr/bin/python
# -*- coding:Utf-8 -*-

import sys
import socket
from thread import start_new_thread


class Broker():
    def __init__(self, ip, port):
        self.s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
        self.s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
        self.ip = ip
        self.port = port
        self.s.bind((ip, port))
        self.listclients = []

def listenMod(b):
    dic = {}
    msg, ip = b.s.recvfrom(1024)
    dic[msg] = ip
    b.listclients.append(dic)
    print msg, " is connected."


def broker(arg):
    try:
        b = Broker(arg[2], int(arg[3]))
        start_new_thread(listenMod, (b, ))

    except Exception, e:
        print e
        sys.exit(-1)


def client(arg):
    try:
        pass
    except:
        pass

def usage():
    print "usage ./udps.py <-b|-c> <args>"
    print "-b\tserver mode\n\t<args>: host port"
    sys.exit()

def main():
    i = 1
    if len(sys.argv) > 1:
        while i < len(sys.argv):
            if sys.argv[1] == "-b":
                broker(sys.argv)
            elif sys.argv[1] == "-c":
                pass
            else:
                usage()
    else:
        usage()



if __name__ == '__main__':
    main()

It always prints "[Errno 48] Address already in use"

I'm using this because I would like to be able do to some special things with my clients but also be able to connect new clients at the same time.

ZeenaZeek
  • 271
  • 3
  • 5
  • 16

1 Answers1

0

First, don't use SO_REUSEADDR. There are legitimate uses of SO_REUSEADDR, but in most simple cases it is not useful, and it hides the real problem. Feel free to re-add it if needed, but only when your program works without it.

Your problem here is in your main. You are looping on the number of arguments, but never increment i, so it loops infinitely. Also you are always testing argv[1]. If there are 4 arguments, and the 2nd is '-b', you will call broker() 4 times, which will obviously not work. Also, note that if your loop ends and the main exit, your program will terminate immediately, so you should at least add a while(True): sleep(5) at the end, but it's not a solution.

Community
  • 1
  • 1
ElderBug
  • 5,926
  • 16
  • 25
  • Thanks for your answer. I use SO_REUSEADDR cause my code is designed to make an UDP Hole Punching prototype. – ZeenaZeek Jan 30 '15 at 13:55
  • @ZeenaZeek Hole punching doesn't require SO_REUSEADDR. But well, if you need it for your implementation it's not a problem. SO_REUSEADDR isn't bad in itself, just keep in mind that it can hide potential problems. – ElderBug Jan 30 '15 at 14:18