Sobes.tech
Junior — Middle

What are the main differences between TCP and UDP protocols in network communication?

sobes.tech AI

Answer from AI

Main differences between TCP and UDP protocols:

  • Reliability: TCP is a reliable protocol that ensures data delivery, error checking, and retransmission of lost packets. UDP is unreliable and does not guarantee delivery.

  • Connection establishment: TCP establishes a connection through a three-way handshake, while UDP is connectionless.

  • Speed: UDP is faster because it does not spend time on connection setup and delivery control.

  • Order of delivery: TCP guarantees that data will arrive in the same order it was sent. UDP does not guarantee order.

  • Usage: TCP is suitable for applications where reliability is important (web, email, files). UDP is used for applications where speed is crucial and some data loss is acceptable (streaming, gaming, VoIP).

Example of TCP usage in Python:

import socket

sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)  # TCP
sock.connect(('example.com', 80))

sock.sendall(b'GET / HTTP/1.1\r\nHost: example.com\r\n\r\n')
response = sock.recv(4096)
print(response.decode())
sock.close()

Example of UDP usage:

import socket

sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)  # UDP
sock.sendto(b'Hello', ('example.com', 12345))
data, addr = sock.recvfrom(1024)
print(data.decode())
sock.close()