Example #1
0
 def __init__(self, port):
     self.stopped = False
     self.host = ""
     self.port = port
     #
     self.users = dict()
     self.userLock = threading.Lock()
     self.connections = dict()
     self.conLock = threading.Lock()
     #
     for i in range(180): # try 3 minutes to bind the socket
         try:
             self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
             self.sock.bind((self.host, self.port)) # bind socket to localhost:port
             dprint("Port is set to: " + str(self.port))
             dprint("Address bound successfully.")
             break
         except OSError:
             if i == 0: lprint("Address not available yet, waiting...")
             self.sock.close()
             print("\rTime passed: " + str(i+1) + "s", end="", flush=True)
             time.sleep(1)
     else:
         sys.exit(2) # could not bind to address
     #
     self.msgcenter_thread = MSGCenterThread(self)
     self.manage_thread = ManageThread(self)
     self.accept_thread = AcceptThread(self.sock, self)
     self.console_thread = ConsoleThread(self)
     lprint("Server started successfully on port " + str(self.port))
Example #2
0
    def run(self):
        self.sock.listen(3) # 3 as TEMP value
        while not self.shouldStop:
            try: conn, addr = self.sock.accept()
            except socket.timeout: continue
            lprint("<" + self.name + "> Incoming connection from:", addr)
            self.parentServer.addConnection((conn, addr))

        self.shutdownMsg()
Example #3
0
    def run(self):
        self.sock.listen(3)  # 3 as TEMP value
        while not self.shouldStop:
            try:
                conn, addr = self.sock.accept()
            except socket.timeout:
                continue
            lprint("<" + self.name + "> Incoming connection from:", addr)
            self.parentServer.addConnection((conn, addr))

        self.shutdownMsg()
Example #4
0
 def stop(self):
     lprint("Shutting down server...")
     self.msgcenter_thread.end()
     self.manage_thread.end()
     self.console_thread.end()
     self.accept_thread.end()
     self.accept_thread.join()
     self.msgcenter_thread.join()
     self.manage_thread.join()
     self.closeAllConnections()
     #self.sock.shutdown(socket.SHUT_RDWR)
     self.sock.close()
     self.stopped = True
Example #5
0
    def run(self):
        while not self.shouldStop:
            self.msgLock.acquire()
            while len(self.pendingMsgs) > 0: # has pending messages
                self.sock.sendall(bytes(repr(self.pendingMsgs.pop(0)), "UTF-8"))
            self.msgLock.release()

            try: data = self.sock.recv(1024)
            except socket.timeout: continue
            except ConnectionResetError: break
            if not data: break
            else: #lprint("[Client " + str(self.ID) + "] " + str(data, "UTF-8"))
                message = str(data, "UTF-8").strip()
                self.parentServer.routeMessage(message, self.ID)
        
        self.sock.close()
        lprint("<" + self.name + "> Connection " + str(self.addr) + " closed.")
        GarbageThread(self.parentServer, self.ID).start()
        self.shutdownMsg()
Example #6
0
    def run(self):
        while not self.shouldStop:
            self.msgLock.acquire()
            while len(self.pendingMsgs) > 0:  # has pending messages
                self.sock.sendall(bytes(repr(self.pendingMsgs.pop(0)),
                                        "UTF-8"))
            self.msgLock.release()

            try:
                data = self.sock.recv(1024)
            except socket.timeout:
                continue
            except ConnectionResetError:
                break
            if not data: break
            else:  #lprint("[Client " + str(self.ID) + "] " + str(data, "UTF-8"))
                message = str(data, "UTF-8").strip()
                self.parentServer.routeMessage(message, self.ID)

        self.sock.close()
        lprint("<" + self.name + "> Connection " + str(self.addr) + " closed.")
        GarbageThread(self.parentServer, self.ID).start()
        self.shutdownMsg()
Example #7
0
def main():
    port = 13370 # default port
    for arg in sys.argv:
        if arg == "-d":
            slog.DEBUG = True
        elif arg.startswith("-p="):
            try: port = int(arg[3:])
            except ValueError: lprint("Invalid port: " + arg[3:], mtype=1)
        elif arg in ["-h", "-help", "-?"]:
            print("Arguments:" +
                    "\n -d       :show debug messages" +
                    "\n -p=<int> :set port number" +
                    "\n -h       :show this help")
            return

    socket.setdefaulttimeout(3) # set default timeout of all sockets
    server = Server(port) # bind to port
    server.serve() # start listening
    while not server.stopped:
        try: time.sleep(1)
        except KeyboardInterrupt:
            lprint("Received keyboard interrupt signal; use command 'stop' to quit instead.")
            break
        if slog.DEBUG: break
Example #8
0
 def ls(self):
     self.conLock.acquire()
     if len(self.connections) > 0:
         lprint("Listing all Connections:")
         self.userLock.acquire()
         for client_id in self.connections:
             lprint("ID " + str(self.connections[client_id].getID()) + ": "
                     + str(self.connections[client_id].getAddr()) + " "
                     + "'" + self.users[client_id] + "'")
         self.userLock.release()
     else: lprint("No connections established.")
     self.conLock.release()
Example #9
0
 def run(self):
     while not self.shouldStop:
         stdinput = sys.stdin.readline() # blocking call
         command = stdinput.strip()
         if command != "":
             dprint("<Console> Echoing input: " + command)
         if command.lower() in ["h", "help", "?"]:
             lprint("<Console> Available commands: stop/q, ls/list, kickid, " +
                    "broadcast, send..to")
         elif command.lower() in ["stop", "q"]:
             self.parentServer.stop()
             break
         elif command.lower() in ["ls", "list"]:
             self.parentServer.ls()
         elif command.lower().startswith("kickid "):
             try: cid = int(command[7:].strip())
             except ValueError:
                 lprint("Invalid id for kickid command: '" + cid + "'")
                 continue
             if cid in self.parentServer.connections:
                 self.parentServer.closeConnection(cid)
             else: lprint("<Console> ID '" + str(cid) + "' is not present on this server.", mtype=1)
         elif command.lower().startswith("broadcast "):
             message = command[10:]
             self.parentServer.broadcast("[Server] " + message)
             lprint("<Console> Broadcast done.")
         elif re.search('send .+ to ', command):
             message = re.search("send .* to", command).group().replace("send ", "", 1).replace(" to", "", 1)
             recipient = re.search('to .*', command).group().replace("to ", "", 1)
             dprint("<Console> message='" + message + "', recipient='" + recipient + "'")
             try:
                 recipient = int(recipient)
                 self.parentServer.sendToClient("[Server] " + message, recipient)
                 lprint("<Console> Message sent to client.")
             except ValueError: lprint("<Console> Invalid recipient.")
         else:
             lprint("Don't know what to do with: '" + command + "'", mtype=3)
     self.shutdownMsg()
Example #10
0
 def run(self):
     while not self.shouldStop:
         stdinput = sys.stdin.readline()  # blocking call
         command = stdinput.strip()
         if command != "":
             dprint("<Console> Echoing input: " + command)
         if command.lower() in ["h", "help", "?"]:
             lprint(
                 "<Console> Available commands: stop/q, ls/list, kickid, " +
                 "broadcast, send..to")
         elif command.lower() in ["stop", "q"]:
             self.parentServer.stop()
             break
         elif command.lower() in ["ls", "list"]:
             self.parentServer.ls()
         elif command.lower().startswith("kickid "):
             try:
                 cid = int(command[7:].strip())
             except ValueError:
                 lprint("Invalid id for kickid command: '" + cid + "'")
                 continue
             if cid in self.parentServer.connections:
                 self.parentServer.closeConnection(cid)
             else:
                 lprint("<Console> ID '" + str(cid) +
                        "' is not present on this server.",
                        mtype=1)
         elif command.lower().startswith("broadcast "):
             message = command[10:]
             self.parentServer.broadcast("[Server] " + message)
             lprint("<Console> Broadcast done.")
         elif re.search('send .+ to ', command):
             message = re.search("send .* to", command).group().replace(
                 "send ", "", 1).replace(" to", "", 1)
             recipient = re.search('to .*',
                                   command).group().replace("to ", "", 1)
             dprint("<Console> message='" + message + "', recipient='" +
                    recipient + "'")
             try:
                 recipient = int(recipient)
                 self.parentServer.sendToClient("[Server] " + message,
                                                recipient)
                 lprint("<Console> Message sent to client.")
             except ValueError:
                 lprint("<Console> Invalid recipient.")
         else:
             lprint("Don't know what to do with: '" + command + "'",
                    mtype=3)
     self.shutdownMsg()