How To Implement A TCP Server In Python And The Differences Between TCP And UDP

This article tells you the difference between TCP and UDP. It will also tell you how to implement a TCP server in Python.

1. The Difference Between TCP And UDP.

  1. The TCP protocol is connection-oriented,  it needs a handshake to confirm the connection, and when it confirms the connection has been created then you can transform data. But UDP is not connection-oriented.
  2. TCP protocol transfers data in order, but UDP protocol does not transfer data in order.
  3. TCP protocol resend lost packets but UDP protocol will not.
  4. TCP protocol discards duplicate packets but UDP protocol will not.
  5. TCP protocol creates error-free data transmission but UDP protocol does not care about the transferred data packet.
  6. TCP protocol will block the network connection and UDP is not, so TCP protocol will cost more resources of the server-side than UDP protocol, UDP protocol is a lightweight protocol.

2. Use Python To Implement A TCP Socket Server Example.

# Create the python server socket object.
tcp_server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

# Get the local address info.
address = ('', 7788)

# Bind the server socket to the local address.

# Invoke the server socket object's listen method to wait for the client to request a connection, the listen method argument is the server port number.

# If a new client requests the server, a new socket will be created to serve the client.
# client_socket is used to serve this client, tcp_server_socket can continue to wait for requests from other new clients.
client_socket, clientAddr = tcp_server_socket.accept()

# Receive the data sent by the client through the client_socket object. It will receive 1024 bytes at one time.
recv_data = client_socket.recv(1024)  
print('The received data is:', recv_data.decode('utf-8'))

# Send back some data to the requesting client.
client_socket.send("thank you !".encode('utf-8'))

# Close the socket serving this client. As long as it is closed, it means that it can no longer serve this client. If the client needs the service again, it can only reconnect again.


Leave a Comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.