0% found this document useful (0 votes)
9 views

ChatGPT - Python tcp chat

Uploaded by

lang.tobias1995
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
9 views

ChatGPT - Python tcp chat

Uploaded by

lang.tobias1995
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 1

https://chatgpt.

com

[python]: Sure, I'll help you create a simple text chat server and client that can connect through a
network and support file transfers. We'll use Python's `socket` library for network communication
and handle file transfers by sending the file in chunks.

Here is an outline of the steps we'll follow:

1. Server:

Accept multiple client connections.

Handle incoming messages and broadcast them to all connected clients.

Support file transfers by receiving file data and saving it to the server.

2. Client:

Connect to the server.

Send messages to the server.

Receive messages from the server.

Support file transfers by reading a file and sending it to the server.

Let's start by writing the server code.

Server Code
python Copy code

import socket
import threading

# Constants
HOST = '127.0.0.1' # Localhost
PORT = 65432 # Port to listen on
BUFFER_SIZE = 1024

clients = []

def handle_client(client_socket, addr):


print(f"New connection: {addr}")
while True:
try:
message = client_socket.recv(BUFFER_SIZE).decode()
if message.startswith("FILE"):
filename = message.split()[1]
filesize = int(message.split()[2])
with open(filename, "wb") as f:
data = client_socket.recv(BUFFER_SIZE)
total_received = len(data)
f.write(data)
while total_received < filesize:
data = client_socket.recv(BUFFER_SIZE)
total_received += len(data)
f.write(data)
print(f"Received file: {filename}")
else:
broadcast(message, client_socket)
except:
clients.remove(client_socket)
client_socket.close()
break

def broadcast(message, client_socket):


for client in clients:
if client != client_socket:
try:
client.send(message.encode())
except:
clients.remove(client)
client.close()

def main():
server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server.bind((HOST, PORT))
server.listen()
print("Server started, waiting for connections...")

while True:
client_socket, addr = server.accept()
clients.append(client_socket)
thread = threading.Thread(target=handle_client, args=(client_socket, addr))
thread.start()

if __name__ == "__main__":
main()

Client Code
python Copy code

import socket
import threading
import os

# Constants
HOST = '127.0.0.1' # The server's hostname or IP address
PORT = 65432 # The port used by the server
BUFFER_SIZE = 1024

def receive_messages(client_socket):
while True:
try:
message = client_socket.recv(BUFFER_SIZE).decode()
print(message)
except:
print("An error occurred.")
client_socket.close()
break

def send_file(client_socket, filepath):


if os.path.isfile(filepath):
filesize = os.path.getsize(filepath)
client_socket.send(f"FILE {os.path.basename(filepath)} {filesize}".encode())
with open(filepath, "rb") as f:
while (data := f.read(BUFFER_SIZE)):
client_socket.sendall(data)
print(f"Sent file: {filepath}")
else:
print("File does not exist.")

def main():
client_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
client_socket.connect((HOST, PORT))

receive_thread = threading.Thread(target=receive_messages, args=(client_socket,))


receive_thread.start()

while True:
message = input()
if message.startswith("SEND"):
filepath = message.split()[1]
send_file(client_socket, filepath)
else:
client_socket.send(message.encode())

if __name__ == "__main__":
main()

Explanation

Server Code:

The server listens for connections and handles each client in a separate thread.

It can receive regular text messages or file transfers. For file transfers, it receives the file
name and size, then reads the file data in chunks and saves it.

The `broadcast` function sends received messages to all clients except the sender.

Client Code:

The client connects to the server and starts a thread to listen for incoming messages.

The main thread reads user input and sends it to the server. If the input starts with "SEND",
it treats it as a file transfer command and sends the specified file to the server.

You can run the server code first and then run multiple instances of the client code to connect to the
server and start chatting or transferring files.



Fri Jun 07 2024 19:22:36 GMT+0200 (Central European Summer Time)

Created by JUST ONE PAGE PDF

You might also like