Reduce server code and keep it working basicly

FIXME welcome message sending after 2 received message
BUG server crash when a client quit
This commit is contained in:
Fred Z 2018-02-27 11:07:47 +01:00
parent f619776b42
commit 41aac322c9
1 changed files with 15 additions and 23 deletions

View File

@ -6,57 +6,49 @@ server.py
Networking test, client-server talking script
"""
import socket
import select
import select, socket
HOST = ''
PORT = 12800
PORT = 5555
BUFFER = 1024
MSG_NEW_CLIENT = "Nouveau client: {}"
MSG_CLIENT_ID = "Client[{}] {}"
MSG_CLIENT_DISCONNECTED = "Le client {} c'est deconnecté"
MSG_CLOSE_CLIENT = "Fermeture socket client {}"
MSG_SERVER_STOP = "Arrêt du serveur"
MSG_START_SERVER = "Le serveur écoute à présent sur le PORT {}"
MSG_WELCOME = "MSG_WELCOME".encode()
STOP_COMMAND = "fin"
connections_list = []
inputs = []
# Creation de la connection
MAIN_CONNECTION = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
MAIN_CONNECTION.bind((HOST, PORT))
MAIN_CONNECTION.listen(5)
server_on = True
connections_list.append(MAIN_CONNECTION)
inputs.append(MAIN_CONNECTION)
print(MSG_START_SERVER.format(PORT))
while server_on:
while 1:
# get the list of sockets which are ready to be read through select
# timeout 50ms
rlist, wlist, xlist = select.select(connections_list, [], [], 0.05)
rlist, wlist, xlist = select.select(inputs, [], [], 0.05)
for socket in rlist:
# Listen for new client connection
if socket == MAIN_CONNECTION:
socket_object, socket_addr = socket.accept()
connections_list.append(socket_object)
inputs.append(socket_object)
print(MSG_NEW_CLIENT.format(socket_addr))
else: # receiving data
print(socket)
try:
data = socket.recv(BUFFER)
except :
print(MSG_CLIENT_DISCONNECTED.format(socket_addr))
socket.close()
connections_list.remove(socket)
continue
data = socket.recv(BUFFER).decode().strip()
socket.send(MSG_WELCOME)
print(MSG_CLIENT_ID.format(socket.getpeername(), data))
msg = data.decode()
socket.send(b"-ok-")
print(MSG_CLIENT_ID.format(socket.getpeername(), msg))
print(MSG_CLOSE_CLIENT.format(socket.getpeername()))
socket.close()
inputs.remove(socket)
print(MSG_SERVER_STOP)
MAIN_CONNECTION.close()