ChatGPT - Python tcp chat
ChatGPT - Python tcp chat
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.
1. Server:
Support file transfers by receiving file data and saving it to the server.
2. Client:
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 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 main():
client_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
client_socket.connect((HOST, PORT))
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)