create a tcp server in python

In Python, creating a TCP server requires the use of the socket module. The following code demonstrates how to create a simple TCP server in Python:

main.py
import socket

# create a socket object
server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

# bind the socket to a public host, and a well-known port
server_socket.bind(("localhost", 5000))

# become a server socket
server_socket.listen(1)

print("TCP server listening...")

while True:
    # accept connections from clients
    client_socket, address = server_socket.accept()

    # receive data from clients
    data = client_socket.recv(1024)
    print("Received from client:", data.decode())

    # send response to clients
    response = "Hello, client!"
    client_socket.send(response.encode())

    # close the client socket
    client_socket.close()
674 chars
28 lines

The socket.AF_INET parameter specifies the address family (IPv4) and the socket.SOCK_STREAM parameter specifies the socket type (TCP). The bind() method binds the socket to the specified host and port. The listen() method enables the server to accept incoming client connections.

The server enters a loop and waits for incoming client connections. When a connection is accepted, the client socket and address are returned by accept(). The server then receives data from the client using recv(), sends a response using send() and closes the client socket using close(). This loop repeats indefinitely, allowing the server to handle multiple clients simultaneously.

gistlibby LogSnag