2

I am trying to write a simple server that will listen for one set of messages on UDP and another set of messages on TCP. I have written the following code:

from threading import Thread
import time
import socket 

#define UDP listening function
def UDPListen():
    Listening_UDP_Port = 300
    Listening_IP = "127.0.0.1"
    BUFFER_SIZE = 64

    sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) # IPv4, UDP
    sock.bind((Listening_IP, Listening_UDP_Port))

    while True:
        data, address = sock.recvfrom(BUFFER_SIZE)
        print "UDP Messsage from address: ", address
        print "Message: ", data

# END UPDListen() FUCNTION


#define a TCP listening function
def TCPListen():
    Listening_TCP_Port = 300
    Listening_IP = "127.0.0.1"
    BUFFER_SIZE = 64

    sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) # IPv4, TCP
    sock.bind((Listening_IP, Listening_TCP_Port))

    while True:
        sock.listen(1)
        conn, address = sock.accept()
        print "TCP connection from", address
        data = conn.recv(BUFFER_SIZE)
        print "Mesage: ", data
        conn.close()

# END TCPListen() FUCNTION


# main function
def main():
    ThreadUDP = Thread(target=UDPListen)
    ThreadTCP = Thread(target=TCPListen)

    print "Starting Server..."
    ThreadUDP.start()
    ThreadTCP.start()
    print "Server Started!"

#END main() FUNCTION


if __name__ == "__main__":
    main()

However when I run it in Python 2.7 it throws a wobbly, any ideas where I am going wrong?

1 Answers1

2

For me on Windows it launches fine as it is.

For linux you'll have to run it as root or use sudo

e.g.

sudo python ./yourserver.py

Or else change your port number to 1024 or above.

It's ok that they have the same port number. If it were 2 tcp service though it wouldn't be ok. See here.

Edit:

Given the OP's clarification of the real issue the solution is to use.

sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)

After creating the sockets. Where sock is your socket name.

Community
  • 1
  • 1
Paul Rooney
  • 20,879
  • 9
  • 40
  • 61
  • Thanks for your advice, I realised this morning that it was because the server doesn't close the ports when the process is killed it. So I had to restart the machine. Will need to find a nice way to close it down when its finished. Thanks again. – Thomas Morgan Mar 13 '15 at 10:52