TCP IP Socket programming using Python

This blog article shows you how to create a simple TCP listener and client. This code sets up a basic TCP server using Python’s socket module. Here’s a step-by-step explanation:

#1. Import the socket module:
import socket

#2.  Create a TCP socket

server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

3. # Bind the socket to a specific address and port

server_socket.bind((‘localhost’, 18999))

4. # Listen for incoming connections

server_socket.listen()
print(“Server is listening on port 18999…”)
try:
     while True:
        5.  # Accept a client connection
         client_socket, client_address = server_socket.accept()
         print(f”Accepted connection from {client_address[0]}:{client_address[1]}”)
         6. # Receive data from the client
         data = client_socket.recv(1024)
         print(f”Received data: {data.decode()}”)
        7.  # Send a response back to the client
         response = “Hello from the server!”
         client_socket.send(response.encode())
        8. # Close the client connection
         client_socket.close()
except KeyboardInterrupt:
     print(“Server stopped by user”)

9. # Close the server socket

server_socket.close()

clip_image002

Also: Create a Selection Sort in C# using GitHub Copilot

The following script is a simple TCP client that connects to a server, sends a message, and receives a response. Here’s a step-by-step explanation:

# 1. Import the socket module:
import socket

# 2. Define the server’s IP address and port

server_ip = ‘localhost’
server_port = 18999

# 3. Create a TCP socket

client_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
try:
     # 4.  Connect to the server
     client_socket.connect((server_ip, server_port))
     # 5. Send the message to the server
     message = ‘Hello’
     client_socket.sendall(message.encode())
     # 6. Receive the response from the server
     response = client_socket.recv(1024)
     print(‘Response from server:’, response.decode())

finally:
     # 7. Close the socket

     client_socket.close()

The script follows a typical pattern for TCP client communication: create a socket, connect to a server, send data, receive data, and close the socket.

clip_image002[5]

Source code download: https://github.com/chanmmn/python/tree/main/2024/PythonTCPProgaming?WT.mc_id=DP-MVP-36769

Reference: https://realpython.com/python-sockets/?WT.mc_id=DP-MVP-36769





Unknown's avatar

About chanmingman

Since March 2011 Microsoft Live Spaces migrated to Wordpress (http://www.pcworld.com/article/206455/Microsoft_Live_Spaces_Moves_to_WordPress_An_FAQ.html) till now, I have is over 1 million viewers. This blog is about more than 50% telling you how to resolve error messages, especial for Microsoft products. The blog also has a lot of guidance teaching you how to get stated certain Microsoft technologies. The blog also uses as a help to keep my memory. The blog is never meant to give people consulting services or silver bullet solutions. It is a contribution to the community. Thanks for your support over the years. Ming Man is Microsoft MVP since year 2006. He is a software development manager for a multinational company. With 25 years of experience in the IT field, he has developed system using Clipper, COBOL, VB5, VB6, VB.NET, Java and C #. He has been using Visual Studio (.NET) since the Beta back in year 2000. He and the team have developed many projects using .NET platform such as SCM, and HR based applications. He is familiar with the N-Tier design of business application and is also an expert with database experience in MS SQL, Oracle and AS 400.
This entry was posted in .Net, Cloud, Community, Computers and Internet, programming and tagged . Bookmark the permalink.

Leave a comment

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