TCP/IP Programing in Python

Generally, a client will be given a randomly selected port number. If you had two clients connecting to the server at once, there would have to be a unique port combo for each connection [1], and the highest port numbers are usually all available for this purpose.

If it’s working, then that’s a good indication that it’s right :slight_smile: You can check the docs here socket — Low-level networking interface — Python 3.13.1 documentation and see that it returns a pair of values.

For your next enhancement, I recommend making the server able to accept more than one client. Right now, only one client can connect, and once that client quits, the server shuts down too. Can you find the right place to wrap a “while True:” around it so that you can handle another client afterwards?

Once that’s working, the next thing will be to have more than once client at the same time. That’ll be a fun challenge, there are several approaches to take.

Have fun!


  1. specifically, every TCP/IP connection needs to have a unique tuple of (client IP, client port, server IP, server port) ↩︎

Thank you for reply. Thanks for the advice. Yes, I agree I need to add another client in the network. This means there will be one server and two clients in the network.

I already have ECHO server working with one client. I just need to add another client. I will try this.

1 Like

Hello, I manage to run one TCP/IP Server and two TCP/IP Clients. The programs are mentioned below.

# TCP_IP_Server.py

print("TCP/IP Chat Room - Server")

import socket
import threading

host = socket.gethostname()
port = 59000

# Starting Server
server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server.bind((host, port))
server.listen()

# Lists For Clients and Their Nicknames
clients = []
nicknames = []

def broadcast(message):
    for client in clients:
        client.send(message)

# Handling Messages From Clients
def handle(client):
    while True:
        try:
            # Broadcasting Messages
            message = client.recv(1024)
            broadcast(message)
        except:
            # Removing And Closing Clients
            index = clients.index(client)
            clients.remove(client)
            client.close()
            nickname = nicknames[index]
            broadcast('{} left!'.format(nickname).encode('ascii'))
            nicknames.remove(nickname)
            break

# Receiving / Listening Function
def receive():
    while True:
        # Accept Connection
        client, address = server.accept()
        print("Connected with {}".format(str(address)))

        # Request And Store Nickname
        client.send('NICK'.encode('ascii'))
        nickname = client.recv(1024).decode('ascii')
        nicknames.append(nickname)
        clients.append(client)

        # Print And Broadcast Nickname
        print("Nickname is {}".format(nickname))
        broadcast("{} joined!".format(nickname).encode('ascii'))
        client.send('Connected to server!'.encode('ascii'))

        # Start Handling Thread For Client
        thread = threading.Thread(target=handle, args=(client,))
        thread.start()

receive()
# TCP_IP_Client.py

print("TCP/IP Chat Room - Client")

import socket
import threading

host = socket.gethostname()
port = 59000

# Choosing Nickname
nickname = input("Choose your nickname: ")

# Connecting To Server
client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
client.connect((host, port))

# Listening to Server and Sending Nickname
def receive():
    while True:
        try:
            # Receive Message From Server
            # If 'NICK' Send Nickname
            message = client.recv(1024).decode('ascii')
            if message == 'NICK':
                client.send(nickname.encode('ascii'))
            else:
                print(message)
        except:
            # Close Connection When Error
            print("An error occurred!")
            client.close()
            break

# Sending Messages To Server
def write():
    while True:
        message = '{}: {}'.format(nickname, input(''))
        client.send(message.encode('ascii'))

# Starting Threads For Listening And Writing
receive_thread = threading.Thread(target=receive)
receive_thread.start()

write_thread = threading.Thread(target=write)
write_thread.start()

I am wondering how to end the program/application. At the moment the application is running all the time. I would like when a Client says “bye” then it should be deleted and when all the Clients are left then the Server should close. Something like this. Any help how to implement the logic to quit the program ?

Yes, you can run this example program (and any tcp/ip program really) on the same system. In this case, just open two terminal windows and run the server in one and the client in the other.