4

I'm a beginner in python (2.6/2.7) who has been thrown in the deep end to create a network service to an existing python app.

I've got a UDP server up and running which works just great but I'm asking for help in making it slightly more bullet proof.

Here is the base code I have written, the usual standard boiler plate:

import sys
import socket
from threading import Thread

def handleInput():
         sock = socket.socket( socket.AF_INET, socket.SOCK_DGRAM )
         sock.bind( ("127.0.0.1",5005) )
         # socket always binded?
         while True:
                 data, addr = sock.recvfrom(512)
                 # is 'data' usable?

t=Thread(target=handleInput)
t.daemon=True
t.start()
# can thread die?

Firstly, I understand that the socket is in a sense always available, it doesn't have to listen, so there is no such thing as failing and you have to reconnect. Is this correct?

Secondly, the issue with returned data from recvfrom. Is it a simple 'if data : then' to check if its valid?

Thirdly, and finally, the thread. Can a thread bomb out? If it does whats the best way to restart it?

Any other tips would be welcome.

(Note: I cannot use external libraries, e.g. twisted etc.)

kingsaul
  • 243
  • 1
  • 2
  • 7
  • 1
    What are you hoping to accomplish with the `Thread` code above? As it stands, there is no value added beyond simply running `handleInput()`, but the whole script will still block until finished with one client. Are you hoping to handle multiple "clients" concurrently? – Mike Pennington May 02 '12 at 09:12
  • This code will be injected into another python app, thats the reason for the thread. As for concurrency, won't the messages from multiple clients be all queued up? – kingsaul May 02 '12 at 15:03

1 Answers1

4

Some answers for your questions:

  1. UDP sockets are connectionless, and as such "always available". Please also be aware that the UDP message length is limited to 65535 bytes IIRC.
  2. Data is just a string, and its validity will depend on the used protocol. Your if data: ... will work as a test for receiving something, but the recvfrom() call will block anyway until it receives something so this seems superfluous.
  3. I have no knowledge about python thread reliability in general.

I would also check the SocketServer module and the associated UDPServerclass - this might make for easier implementation. The SocketServer is part of python's standard library.

jhonkola
  • 3,385
  • 1
  • 17
  • 32
  • 1
    Theoretically, the maximum size of an IP datagram is 65535 bytes, imposed by the 16-bit total length field in the IP header. With an IP header of 20 bytes and a UDP header of 8 bytes, this leaves a maximum of 65507 bytes of user data in a UDP datagram. Most implementations, however, provide less than this maximum. – Art Swri May 02 '12 at 14:50