add client and server implementation for socket communication

This commit is contained in:
2025-02-25 10:25:17 +01:00
parent 14f076a85b
commit e2350d4b35
4 changed files with 92 additions and 8 deletions

5
.gitignore vendored
View File

@@ -2,4 +2,7 @@
.idea/*
.venv
.venv/*
.venv/*
.winvenv
.winvenv/*

36
TP7/7.3/client.py Normal file
View File

@@ -0,0 +1,36 @@
import socket
import threading
def receive_messages(client_socket):
try:
while True:
msg = client_socket.recv(1024)
if msg.decode() == 'stop':
print('Received stop signal. Closing connection.')
break
else:
print(f'Message received: {msg.decode()}')
except Exception as e:
print(f'Error: {e}')
finally:
client_socket.close()
client_socket = socket.socket()
client_socket.connect(('localhost', 12345))
client_socket.send('Coucou'.encode())
# Ask the user for messages to send
try:
while True:
msg = input('Message: ')
client_socket.send(msg.encode())
if msg == 'stop':
break
except KeyboardInterrupt:
print('Connection closed')
finally:
client_socket.close()
receive_thread = threading.Thread(target=receive_messages, args=(client_socket,))
receive_thread.start()
receive_thread.join()

52
TP7/7.3/server.py Normal file
View File

@@ -0,0 +1,52 @@
import socket
import threading
clients = []
def send_to_all(clients, message):
for client in clients:
try:
client.send(message)
except Exception as e:
print(f'Error sending message to a client: {e}')
clients.remove(client)
def client_thread(client_socket, clients):
try:
while True:
msg = client_socket.recv(1024)
if msg:
print(f'Message received: {msg.decode()}')
send_to_all(clients, msg)
else:
break
except Exception as e:
print(f'Error: {e}')
finally:
client_socket.close()
clients.remove(client_socket)
server_socket = socket.socket()
server_socket.bind(('', 12345))
server_socket.listen()
print('Server is listening for connections...')
try:
while True:
client_socket, addr = server_socket.accept()
print(f'Connection from {addr}')
clients.append(client_socket)
thread = threading.Thread(target=client_thread, args=(client_socket, clients))
thread.start()
except KeyboardInterrupt:
print('Server stopped')
finally:
for client in clients:
try:
client.shutdown(socket.SHUT_RDWR)
except Exception as e:
print(f'Error shutting down client socket: {e}')
client.close()
server_socket.close()
print('Server closed')

View File

@@ -1,7 +0,0 @@
if __name__ == '__main__':
a='1'
b=int(a)
print(type(a))
print(type(b))
print(ord('a'))
print(chr(97))