Home > Coding > python > Socket Programming in Python – Two-Way Client-Server Chat in PyCharm on Port 8443

Socket Programming in Python – Two-Way Client-Server Chat in PyCharm on Port 8443

Let’s level up our networking game—socket programming in Python, all in PyCharm, no VMs needed! We’ll simulate a client and server chatting both ways on port 8443—client can ping server, server can ping client, anytime. Plus, we’ll keep the file transfer trick up our sleeve. It’s lazy, it’s two-way. Let’s Go.


Why Two-Way Chat?

  • Full Duplex: Server and client both talk freely—not a one-sided convo.
  • PyCharm Sim: One IDE, one machine—lazy and clean.
  • Port 8443: Random, less crowded than 443—easy testing vibes.

Sockets are your data highways—here, traffic flows both ways.


Setup: PyCharm on One Machine

  • Install PyCharm: Free Community Edition from JetBrains.
  • Python: Verify with python3 –version in terminal.
  • Project: New project in PyCharm (e.g., “SocketChat8443”).

We’ll use 127.0.0.1:8443—localhost looping back.


Server Code: Listen and Chat Both Ways

Create server.py in PyCharm:

python

import socket
import threading

# Create server socket
server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server_socket.bind(('127.0.0.1', 8443))  # Localhost, port 8443
server_socket.listen(1)

print("Server listening on port 8443...")

# Accept client connection
client_socket, addr = server_socket.accept()
print(f"Connected to {addr}")

# Receive messages from client
def receive_messages():
    while True:
        try:
            client_msg = client_socket.recv(1024).decode()
            if not client_msg or client_msg.lower() == "exit":
                print("Client disconnected.")
                break
            print(f"Client: {client_msg}")
        except:
            break

# Send messages to client
def send_messages():
    while True:
        server_msg = input("Server: ")
        client_socket.send(server_msg.encode())
        if server_msg.lower() == "send file":
            with open("server_file.txt", "rb") as f:
                client_socket.send(f.read())
            print("Sent server_file.txt to client!")

# Start threads for two-way chat
receive_thread = threading.Thread(target=receive_messages)
send_thread = threading.Thread(target=send_messages)
receive_thread.start()
send_thread.start()

# Wait for threads to finish
receive_thread.join()
send_thread.join()

# Clean up
client_socket.close()
server_socket.close()

Client Code: Connect and Chat Both Ways

Create client.py in PyCharm:

python

import socket
import threading

# Create client socket
client_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
client_socket.connect(('127.0.0.1', 8443))  # Connect to localhost:8443

print("Client connected to localhost:8443")

# Receive messages from server
def receive_messages():
    while True:
        try:
            server_msg = client_socket.recv(1024).decode()
            if not server_msg:
                print("Server disconnected.")
                break
            print(f"Server: {server_msg}")
            # Bonus: Handle file if "send file" was sent
            if "send file" in server_msg.lower():
                file_data = client_socket.recv(4096)
                with open("received_file.txt", "wb") as f:
                    f.write(file_data)
                print("Received file as received_file.txt!")
        except:
            break

# Send messages to server
def send_messages():
    while True:
        client_msg = input("Client: ")
        client_socket.send(client_msg.encode())
        if client_msg.lower() == "exit":
            print("Disconnecting...")
            break

# Start threads for two-way chat
receive_thread = threading.Thread(target=receive_messages)
send_thread = threading.Thread(target=send_messages)
receive_thread.start()
send_thread.start()

# Wait for threads to finish
receive_thread.join()
send_thread.join()

# Clean up
client_socket.close()

Running in PyCharm

  1. Server First:
    • Right-click server.py > Run ‘server’.
    • Terminal: “Server listening on port 8443…”
    • If 8443’s taken, use 8444—update both scripts.
  2. Client Next:
    • New terminal: Terminal tab > python client.py (or right-click client.py > Run ‘client’).
    • See “Connected to localhost:8443”.
  3. Chat Both Ways:
    • Client: “Hey, server!” > Server sees it.
    • Server: “Yo, client!” > Client sees it.
    • Server: “What’s up?” > Client: “Chillin’!”
    • Client: “How’s it going?” > Server: “Lazy day!”
  4. File Transfer:
    • Server: “send file” > Client gets received_file.txt.
    • Open it: “Lazy Guy rules!”.

Sample Output:

  • Server Terminal:Server listening on port 8443... Connected to ('127.0.0.1', 54321) Client: Hey, server! Server: Yo, client! Client: How’s it going? Server: Lazy day! Server: send file Sent server_file.txt to client!
  • Client Terminal:Connected to localhost:8443 Client: Hey, server! Server: Yo, client! Server: What’s up? Client: Chillin’! Client: How’s it going? Server: Lazy day! Server: send file Received file as received_file.txt!

How Two-Way Works

  • Threads: threading—receive_messages listens, send_messages talks—both run at once for server and client.
  • Port 8443: 127.0.0.1:8443—local loopback, no fuss.
  • Exit: Client types “exit”—both sides shut down cleanly.

Bonus Feature: File Transfer

  • How: Server types “send file”—sends server_file.txt—client saves it after the message.
  • Why: Sockets do more than chat—lazy data mover!
  • Next: Client-to-server transfer—holler if you want it!

Lazy Guy Tips

  • Port Check: If 8443’s busy, netstat -tuln | grep 8443—swap to 8444.
  • PyCharm Debug: Breakpoints—see messages live.
  • Scale: Multi-clients? Tweak server.py—lazy chatroom!
  • Cyber Link: Ports like 8443 face DDoS—QoS could throttle it.

Run it in PyCharm—two-way chat, one machine, all lazy. Drop your hacks below—stay chill, stay connected!

Leave a Comment