I am trying to store a message received from a socket into a variable for later use.
For example, I want to store the second message sent and save it in a variable to use later.
I’ve tried everything, but nothing works, and I keep getting errors.
Heres everything i got sofar:
import socket
import threading
# Constants
HEADER = 1024
PORT = 1002
SERVER = socket.gethostbyname(socket.gethostname())
FORMAT = 'utf-8'
DISCONNECT_MESSAGE = '!DISCONNECT'
# List to store messages
messages = []
# Create and bind the server
server = socket.socket(socket.AF_INET, socket.SOCK_STREAM) # AF_INET = IP, SOCK_STREAM = TCP
server.bind((SERVER, PORT))
def handle_client(client_socket, client_address):
"""Handle communication with a single client."""
print(f"[NEW CONNECTION] {client_address} connected.")
connected = True
while connected:
try:
# Receive the message length
msg_length = client_socket.recv(HEADER).decode(FORMAT)
if msg_length:
msg_length = int(msg_length)
msg = client_socket.recv(msg_length).decode(FORMAT)
# Log and store the message
print(f"[{client_address}] {msg}")
messages.append((client_address, msg)) # Add to the list
print(messages[0])
# Disconnect if the message is the DISCONNECT_MESSAGE
if msg == DISCONNECT_MESSAGE:
connected = False
except Exception as e:
print(f"[ERROR] {e}")
break
client_socket.close()
def start():
"""Start the server and listen for connections."""
server.listen()
print(f"[LISTENING] Server is listening on {SERVER}")
while True:
client_socket, client_address = server.accept()
thread = threading.Thread(target=handle_client, args=(client_socket, client_address))
thread.start()
print(f"[ACTIVE CONNECTIONS] {threading.active_count() - 1}")
print("[STARTING] Server is starting...")
start()
Zylpay is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.
3