1+ from fs .osfs import *
2+ import os ,json ,time ,sys
3+ from colorama import *
4+ import socket
5+ import threading ,asyncio
6+
7+ init (autoreset = True )
8+
9+ def NewConfig ():
10+ # .sconfig structment
11+ """
12+ {
13+ "ip":,
14+ "port":,
15+ "application":[public/audit/whiteonly/verify],
16+ "showinf":,
17+ "maxlink":,
18+ "log":[1/0]
19+ }
20+ """
21+ Sconfig = {}
22+ print (Fore .BLUE + "Welcome to use chatroom server service" )
23+ print (Fore .YELLOW + "You haven't made config file for server.Now let set your server." )
24+ print ("\n " )
25+ Sconfig ["ip" ]= input (Fore .BLUE + "Server IP:" ) #Unsafe input way. /not_exist
26+ Sconfig ["port" ]= int (input (Fore .BLUE + "Server Port:" ))
27+ Sconfig ["application" ]= input (Fore .BLUE + "Server application way:" + Fore .YELLOW + "[public/audit/whiteonly/verify]" )
28+ Sconfig ["showinf" ]= (input (Fore .BLUE + "Server showinf:" + Fore .YELLOW + "[T/F]" )== "T" )
29+ Sconfig ["maxlink" ]= int (input (Fore .BLUE + "Server Maxlink:" ))
30+ Sconfig ["log" ]= (input (Fore .BLUE + "Server Log" + Fore .YELLOW + "[T/F]" )== "T" )
31+ Mf .writetext ("./.sconfig" ,json .dumps (Sconfig ,ensure_ascii = False ))
32+ time .sleep (1 )
33+ print (Fore .RED + "OK! Please restart main.py." )
34+ sys .exit (0 )
35+
36+ def Load ():
37+ try :
38+ global config
39+ config = json .loads (Mf .readtext (".Sconfig" ,encoding = "utf-8" ))
40+ except Exception as inf :
41+ print (Fore .RED + "Load config failed.\n Please check your file.\n Or you can delete ./.Sconfig to reset." )
42+ sys .exit (0 )
43+
44+ class TcpServer :
45+ def __init__ (self ):
46+ self .running = False
47+ self .Userlist = {}
48+ self .server = None
49+ async def start_server (self ):
50+ self .server = await asyncio .start_server (self .handle_client , Mf ["ip" ], Mf ["port" ])
51+ self .running = True
52+ async with self .server :
53+ await self .server .serve_forever ()
54+ def handle_command (self ):
55+ pass
56+
57+ def Create_Server ():
58+ """
59+ 首次加入服务器:["join","[serverip]",{"name":,"ip":,"MAC":,"Device":}]
60+ 已经加入服务器: ["message",{"name":,"ip":,"MAC":,"Device":}]
61+ 正常退出服务器: ["exit",{"name":,"ip":,"MAC":,"Device":}]
62+ """
63+ Server = TcpServer ()
64+ CmdT = threading .Thread (target = Server .handle_command ,daemon = True )
65+ CmdT .start ()
66+
67+ try :
68+ asyncio .run (Server .start_server ())
69+ except :
70+ CmdT .join ()
71+ pass
72+
73+ def main ():
74+ global Mf
75+ Mf = OSFS (os .path .dirname (os .path .abspath (__file__ )))
76+ if not Mf .exists ("./.sconfig" ):
77+ NewConfig ()
78+ Load ()
79+ try :
80+ Create_Server ()
81+ except Exception as errorinf :
82+ pass #need inf
83+
84+ if __name__ == "__main__" :
85+ main ()
0 commit comments