Main Content

TCP v UDP / Client v Server - Python examples

Archive - Originally posted on "The Horse's Mouth" - 2010-03-25 20:41:31 - Graham Ellis

Python's socket module makes it easy for you to write your own clients and server ... and yesterday I produced "Hello World" style examples of each on the final day of our Python Programming Course. I'm going to share these examples with you here ... but I'm also going to add a word of caution first to remind you that if you're programming with a well define protocol such as ssh, http, ntp, nntp, pop3, imap, smtp, snmp, rpc, dhcp, dns, etc, then you'll do far better to use the higher level classes that someone else has already written [http example]. Unusually, the delegates yesterday required to write the protocol themselves.

TCP v UDP

You'll read that you can program sockets using TCP/IP or using UDP ... What's the difference?

Tcp is the most common; in Tcp, the packets are synchronized so that the receiving program will get them without data loss from the sender. So that's ideal for most data interchanges - you send a database backup or a web page over a network, and you want the client to get what has been served exactly.

By contract, Udp packets are sent asynchronously, and if the client doesn't receive them from the server, that's not regarded as a catastrophic failure; you don't want too many dropped packets, but a few is no problem. You might use Udp for a telephone conversation signal, where a click on the line is far better in the event of problems than the whole system lagging to await for a retransmission.

Put it another way - Tcp is connection oriented, with the transmitter verifying the receiver and Udp is connectionless - sending the data irrespective of whether it's received at the far end.

TCP - Transmission Control Protocol
UDP - User Datagram Protocol

Client v Server

There's not as much difference as you think!

The server sits waiting for a connection from any client, whereas the client specifies which server it's to connect into and "goes for it" ... but once they're connected, they chat back and forth very much in balance.

The server needs to stay running awaiting the next connection ... the client to close down and finish.

Samples

I have added comments into each of the following, and tested them too.
TCP/IP Server in Python (test via telnet to the port)
TCP/IP Client in Python (test via our server)
UDP Server in Python (run this server ...)
UDP Client in Python (... then talk to it via this client)