DEV Community

Zephaniah Joshua
Zephaniah Joshua

Posted on

Difference between UDP and TCP (example code)

Hi everybody this is my first post. I started the 100DaysofCodechallenge so I decided to write about what I learn each day.

Today I learnt about the difference between UDP and TCP and used it in the client/server model python code.

UDP(User datagram protocol):

In simple terms UDP is a very fast and not-so-reliable communications protocol and does not need to make connections before sending data.

TCP(Transfer control protocol):

On the other hand TCP makes connections before data is sent, is a reliable transmissions protocol, not as fast UDP.

I will use a simple python server code to show the differences

-A simple server using TCP connection

from socket import * 

#create socket
sockfd = socket(AF_INET, SOCK_STREAM)
#bind socket
sockfd.bind(("127.0.0.1", 9999))
#listen for connections
sockfd.listen()

#accept connection
newsockfd, address = sockfd.accept() 

#recieve message
response = newsockfd.recv(1024)

#send message
message="this message is for you"
newsockfd.send(msg)

Enter fullscreen mode Exit fullscreen mode

-A simple server using UDP connection

#create socket
sockfd = socket(AF_INET, SOCK_DGRAM)

#bind socket
sockfd.bind(("127.0.0.1", 9999))

#recv message
data, client_addr = sockfd.recvfrom(1024)

#send message
message = "yo, yo"
msg = message.encode()
sockfd.sendto(msg, client_addr)
Enter fullscreen mode Exit fullscreen mode

We can clearly see that the UDP code is shorter than the TCP.This is because:

1.TCP connection listen sockfd.listen()for connections on it socket while UDP just doesn't do that(if data is sent and server is not up it is simply lost)

2.TCP accepts connectionnewsockfd, address = sockfd.accept()from the client before exchanging information while UDP just accepts information and stores data, client_addr = sockfd.recvfrom(1024)the IP address from which it received information

3.The receiving function. TCP uses recv(1024) to recv data "1024" specify the amount of data
while UDP uses recvfrom(1024)basically because the address from which the data was received also needs to be store

4.The send function. TCP uses the send() because it does not need to specify the address to which the data needs to be sent
because a connection has already been established between client and server
while the UDP uses sendto()which needs to sppecify the address to which data will be sent.

FTP, SSH, email use TCP.
Streaming media, online gaming use UDP.

Hope this little information gives you a basic understanding of TCP and UDP feel free to live your thoughts in the comments or contact me at black_strok3

Top comments (0)