Created
January 3, 2019 17:02
-
-
Save frankgould/efc34dbdf0b6dab838ea436ab2058308 to your computer and use it in GitHub Desktop.
Rover Battery Capacity Communications Server code
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env python3 | |
"""Server for multithreaded (asynchronous) chat application.""" | |
from socket import AF_INET, socket, SOCK_STREAM, SOL_SOCKET, SO_REUSEADDR | |
from threading import Thread | |
import logging | |
from datetime import datetime | |
log_file = '/home/rover_logs/comm_server-log-' + datetime.now().strftime("%m-%d-%y") + '.txt' | |
logging.basicConfig(filename=log_file,level=logging.DEBUG) | |
logging.info('==================== Rover Battery Capacity Communications Server Logging Started ' + datetime.now().strftime("%m-%d-%y %H:%M:%S")) | |
def accept_incoming_connections(): | |
"""Sets up handling for incoming clients.""" | |
while True: | |
client, client_address = SERVER.accept() | |
logging.info("%s:%s Battery has connected." % client_address) | |
client.send(bytes("Connected", 'utf8')) | |
addresses[client] = client_address | |
Thread(target=handle_client, args=(client,)).start() | |
def handle_client(client): # Takes client socket as argument. | |
"""Handles a single client connection.""" | |
name = client.recv(BUFSIZ).decode('utf8') | |
msg_active = 'Active' | |
client.send(bytes(msg_active, 'utf8')) | |
logging.info(name + ' joined Battery @ ' + datetime.now().strftime("%m-%d-%y %H:%M:%S")) | |
clients[client] = name | |
while True: | |
msg = client.recv(BUFSIZ) | |
logging.info('Battery message received: [' + str(msg) + '] from: ' + str(name) + ' @ ' + datetime.now().strftime("%m-%d-%y %H:%M:%S")) | |
if msg != bytes('{quit}', 'utf8'): | |
broadcast(msg, name+": ") | |
else: | |
client.send(bytes('{quit}', 'utf8')) | |
client.close() | |
del clients[client] | |
logging.info("%s has left the Battery session." % name) | |
break | |
def broadcast(msg, prefix=""): # prefix is for name identification. | |
"""Broadcasts a message to all the clients.""" | |
for sock in clients: | |
sock.send(bytes(prefix, 'utf8')+msg) | |
clients = {} | |
addresses = {} | |
HOST = '' | |
PORT = 33002 | |
BUFSIZ = 1024 | |
ADDR = (HOST, PORT) | |
SERVER = socket(AF_INET, SOCK_STREAM) | |
SERVER.setsockopt(SOL_SOCKET, SO_REUSEADDR, 1) | |
SERVER.bind(ADDR) | |
if __name__ == "__main__": | |
SERVER.listen(5) | |
logging.info("Waiting for Battery connections...") | |
ACCEPT_THREAD = Thread(target=accept_incoming_connections) | |
ACCEPT_THREAD.start() | |
ACCEPT_THREAD.join() | |
SERVER.close() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment