1 module chatroom.server.server; 2 3 import hunt.imf; 4 5 import chatroom.command; 6 import chatroom.chatroom; 7 8 import std.stdio; 9 import std.string; 10 11 12 13 14 class UserInfo : Element 15 { 16 this(Context context , string username) 17 { 18 super(context); 19 this.username = username; 20 } 21 string username; 22 } 23 24 alias ChatRoom = Singleton!(Room!(string,UserInfo)); 25 26 class ChatService 27 { 28 mixin MakeRouter; 29 30 @route(Command.MESSAGE) 31 void recv(Msg message) 32 { 33 ChatRoom.instance.broadCast(Command.MESSAGE , message); 34 } 35 36 @route(Command.Q_LOGIN) 37 void mylogin(Login login) 38 { 39 ChatRoom.instance.findEx(login.name , 40 (UserInfo info){ 41 if(info is null) 42 { 43 auto user = new UserInfo(context , login.name); 44 ChatRoom.instance.add(login.name, user); 45 46 /// notify onlines this one login , except this one. 47 ChatRoom.instance.broadCast(Command.LOGIN , login , login.name); 48 49 /// rely to this one login suc. 50 auto reply = new LoginReply(); 51 reply.status = LoginReply.LoginState.OK; 52 reply.name = login.name; 53 context.sendMessage(Command.R_LOGIN , reply); 54 55 /// set context bind 56 context.setAttachment(user); 57 58 writeln(login.name , " login"); 59 } 60 else 61 { 62 auto reply = new LoginReply(); 63 reply.name = login.name; 64 reply.status = LoginReply.LoginState.FAIL; 65 sendMessage(context , Command.R_LOGIN , reply); 66 } 67 }); 68 69 70 } 71 72 } 73 74 75 int main() 76 { 77 auto app = new Application(); 78 79 auto server = app.createServer("0.0.0.0" , 3003); 80 server.setCloseHandler((Context context){ 81 auto user = cast(UserInfo)context.getAttachment(); 82 if( user !is null) 83 { 84 /// clear attach 85 context.setAttachment(null); 86 87 auto login = new Login(); 88 login.name = user.username; 89 90 /// remove from chatroom 91 ChatRoom.instance.remove(login.name); 92 93 /// notify to all users 94 ChatRoom.instance.broadCast(Command.LOGOUT,login); 95 96 writeln(user.username ~ " logout"); 97 } 98 }); 99 app.run(); 100 return 0; 101 }