old_gravity/server.py

105 lines
2.9 KiB
Python
Executable File

#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sun Jan 26 17:50:25 2020
@author: suwako
"""
import sys, multiprocessing, socket, time
if sys.platform == 'win32':
import multiprocessing.reduction
from colorama import Fore, Style
import numpy as np
def debug(*s): print("[D ] : " +
str(', '.join(map(str, s))) +
Style.RESET_ALL)
def info(*s): print(Fore.GREEN +
Fore.LIGHTGREEN_EX +
"[I -] : " +
Style.RESET_ALL +
str(', '.join(map(str, s))) +
Style.RESET_ALL)
def warn(*s): print(Fore.MAGENTA +
"[W ~] : " +
Style.RESET_ALL +
str(', '.join(map(str, s))) +
Style.RESET_ALL)
def error(*s): print(Fore.RED +
Fore.LIGHTRED_EX +
"[E !] : " +
Style.RESET_ALL +
str(', '.join(map(str, s))) +
Style.RESET_ALL)
level = 1
for i in range(level):
exec("debug info warn error".split()[i] + "= lambda *x: None")
def handle(connection, address):
try:
info("Connected at "+ ':'.join(map(str,address)))
while True:
data = connection.recv(1024)
if data == b"":
info("Socket closed remotely at " + ':'.join(map(str,address)))
break
debug("Received data %r" % data)
connection.sendall(data)
debug("Sent data")
except:
warn("Problem handling request")
connection.close()
raise
finally:
debug("Closing socket with " + ':'.join(map(str,address)))
connection.close()
class Server(object):
def __init__(self, hostname, port):
self.hostname = hostname
self.port = port
def start(self):
debug("listening")
self.socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self.socket.bind((self.hostname, self.port))
self.socket.listen(1)
while True:
conn, address = self.socket.accept()
process = multiprocessing.Process(target=handle,
args=(conn, address))
process.daemon = True
process.start()
if __name__ == "__main__":
server = Server("0.0.0.0", 9000)
try:
info("Listening")
server.start()
except:
error("Unexpected exception")
for process in multiprocessing.active_children():
info("Shutting down process %r", process)
process.terminate()
process.join()
raise
finally:
info("Shutting down")
for process in multiprocessing.active_children():
info("Shutting down process %r", process)
process.terminate()
process.join()
info("All done")