コード例 #1
0
ファイル: ClientListener.cs プロジェクト: budulai/iasiminChat
 public ClientListener(ChatClient chatClient, string ip)
 {
     if (chatClient == null)
         throw new NullReferenceException("Invalid chatClient parameter");
     _chatClient = chatClient;
     _ip = ip;
 }
コード例 #2
0
ファイル: Program.cs プロジェクト: budulai/iasiminChat
        static void Main(string[] args)
        {
            int port = 8001;
            string ip = "127.0.0.1";
            //            string ip = "172.17.50.45";

            ChatClient chatClient = null;
            ChatClient chatClient2 = null;

            try
            {
                chatClient = new ChatClient(ip, port);
                chatClient2 = new ChatClient(ip, port);
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
                return;
            }

            //Decomenteaza liniile ca sa creezi useri
            chatClient.SignUp("Dinu", "MyPassword");
            chatClient2.SignUp("George", "HisPassword");

            chatClient.SignIn("Dinu", "MyPassword");

            Thread.Sleep(100);

            chatClient2.SignIn("George", "HisPassword");
            //            Console.WriteLine("Sending friend request");

            //chatClient.SendFriendRequest("George");
            chatClient2.SendFriendRequest("Dinu");

            chatClient.SetMessageReceiver(ReceiveMessage);
            chatClient2.SetMessageReceiver(ReceiveMessage);
            chatClient.SetFileReceiver(ConfirmFileReceivement,GetSavePath);
            chatClient2.SetFileReceiver(ConfirmFileReceivement, GetSavePath);

            chatClient.SendMessage("George", "Hi George");

            //            chatClient.SendFile("George", @"C:\nap3.gif");
            chatClient.ChangeStatus("Dinu Status");

            chatClient.SignOut();
            chatClient2.SignOut();
        }
コード例 #3
0
ファイル: GuiChat.cs プロジェクト: Maartyl/cs-chan
        static void Init(Settings settings, Connector conn, Action<Connector, ChanStore> initExtra)
        {
            var store = new ChanStore();
              var client = new ChatClient(settings, store, conn);

              //simple default config for now
              var dfltCfg = NetChanConfig.MakeDefault<Message>();

              //client
              var rFailT = store.PrepareClientReceiverForType(dfltCfg);
              var sFailT = store.PrepareClientSenderForType(dfltCfg);
              rFailT.PipeEx(conn, "store: receiver cache");
              sFailT.PipeEx(conn, "store: sender cache");
              conn.Register(Cmd.Send, client.BroadcastMessage);
              conn.Register(Cmd.Connect, client.Connect);
              conn.Register(Cmd.Disconnect, _ => client.Disconnect());
              conn.Register(Cmd.Join, a => {
            var args = (a.Text ?? "").Split(new []{ ' ' }, StringSplitOptions.RemoveEmptyEntries);
            if (args.Length > 2)
              conn.RunError("requires 1 or 2 arguments <?host:port> <name>".ArgSrc("join"));
            else ((Func<Func<string, string, bool>, bool>) (cont => { //I could use ifs; this is more obvious to me...
            switch (args.Length) { //host, name
              case 1:
                return cont(null, args[0]);
              case 2:
                return cont(args[0], args[1]);
              default:
                return cont(null, null);
            } // apply args^ to connect and (name if != null)
              }))((host, name) => conn.RunOrDefault(Cmd.Connect, host) && (name != null) && conn.RunOrDefault(Cmd.Name, name));
              });

              //server
              //it reregisters it's commands if started (to ones created in start fn)
              Action<CmdArg> serverStartOff = null; //~ referenced from itself
              Action<CmdArg> serverStopOff = _ => conn.RunError("not running".ArgSrc("server"));
              serverStartOff = a => {
            var portS = a.Text;
            int port;
            if (!int.TryParse(portS, out port)) {
              //couldn't parse: try default
              if (settings.DefaultServerPort == -1) {
            conn.RunError("requires port (default not allowed)".ArgSrc(Cmd.ServerStart + " " + portS));
            return;
              }
              port = settings.DefaultServerPort;
            }
            //port OK: try creating and starting server:
            try {
              var serverStore = new ChanStore();
              InitServer(settings, serverStore, conn);
              serverStore.StartServer(port);

              //created fine: reregister
              conn.Reregister(Cmd.ServerStart, _ => conn.RunError(("already running (port: " + port + ")").ArgSrc("server")));
              conn.Reregister(Cmd.ServerStop, _ => {
            try {
              serverStore.StopServer();//stop listening for new
              //kill stuff in ChanStore: this will force shut the open channels and close clients
              serverStore.CloseAll().PipeEx(conn, "server.stop (in clear)");

              conn.RunNotifySystem("stopped".ArgSrc("server"));
            } catch (Exception ex) {
              ex.PipeEx(conn, "server.stop");
            } finally {
              conn.Reregister(Cmd.ServerStop, serverStopOff); //use original handlers again
              conn.Reregister(Cmd.ServerStart, serverStartOff);
            }
              });

              conn.RunNotifySystem("started".ArgSrc("server"));
            } catch (Exception ex) {
              ex.PipeEx(conn, Cmd.ServerStart + " " + port);
            }
              };

              conn.Register(Cmd.ServerStart, serverStartOff);
              conn.Register(Cmd.ServerStop, serverStopOff);
              conn.Register(Cmd.Host, async port => {
            try {
              if (string.IsNullOrWhiteSpace(port)) {
            if (settings.DefaultServerPort == -1)
              throw new ArgumentException("requires port (default not allowed)");
            port = settings.DefaultServerPort.ToString();
              }

              if (await conn.RunOrDefaultAsync(Cmd.ServerStart, port)) {
            //~ok: problem: this is run after known, whether Cmd.Server exists, not after server started
            //: connect waits until started; ok
            // - no it doesn't: it cannot: it's elsewhere...
            await Task.Delay(50); //wait a little instead
            await conn.RunOrDefaultAsync(Cmd.Connect, "localhost:" + port);
              }
            } catch (Exception ex) {
              ex.PipeEx(conn, Cmd.Host + " " + port);
            }
              });

              //translate text to send
              conn.Register(Cmd.Text, a => {
            if (!string.IsNullOrWhiteSpace(a))
              conn.RunOrDefault(Cmd.Send, a.Text.Trim());
              });
              //get/change name
              conn.Register(Cmd.Name, a => {
            var arg = a.Text;
            if (string.IsNullOrWhiteSpace(arg)) {
              //get name
              conn.RunNotifySystem(client.ClientName.ArgSrc("clinet name"));
            } else {
              //set name
              client.ClientName = arg;
            }
              });

              //parse line into command and run it
              conn.Register(Cmd.CmdParseRun, a => {
            var ok = Cmd.ParseCommandInto(a, (cmd, arg) => conn.RunOrDefault(cmd ?? Cmd.NoCommand, arg));
            if (ok)
              conn.RunOrDefault(Cmd.CmdAccepted, a);
              });

              //command completion
              conn.Register(Cmd.CompletionRequest, a => {
            string arg = a;
            if (string.IsNullOrWhiteSpace(arg) || arg[0] != Settings.UserCommandStart || arg.Contains(' '))
              //for now: only completion of main command is suppoerted
              return;

            arg = arg.Substring(1); //remove commandStart char (:)
            var possibles = conn.Keys.Where(k => k.StartsWith(arg)).ToArray();
            if (possibles.Length == 0)
              //no option to help with
              return;

            //if more then 1: find longest common prefix (starting at already known: len of arg
            //if 1: append ' ' as it is both useful and shows the cmd is complete
            string completedCmd = possibles.Length == 1 ? possibles[0] + ' '
              : longestCommonPrefix(possibles, arg.Length);
            conn.RunOrDefault(Cmd.CompletionResponse, (Settings.UserCommandStart + completedCmd).ArgSrc(a));
              });

              conn.Reregister(Cmd.AfterGuiLoaded, _ => {
            initExtra(conn, store);

            //in AfterGuiLoaded because Gui registers Exit through Add, not Merge
            conn.Coregister(Cmd.Exit, __ => {
              //dirty way of making sure every WCF server is cosed, so the app doesn't hang after GUI thread finished
              conn.Reregister(Cmd.NotifyError, err => Console.Error.WriteLine(string.Format("{0}:! {1}", err.Source, err.Text)));
              conn.Reregister(Cmd.NotifySystem, err => Console.WriteLine(string.Format("{0}:: {1}", err.Source, err.Text)));
              conn.RunOrDefault(Cmd.Disconnect); //this is probaly not necesary, but why not...
              conn.RunOrDefault(Cmd.ServerStop);
              conn.RunOrDefault(Cmd.WsdlStop);
            });
              });

              conn.Register(Cmd.Wsdl, a => {
            int port;
            if (!int.TryParse(a, out port)/*try port from argument*/
            && (port = settings.DefaultWsdlPort) < 0/*try default; if (<0):*/
            && conn.RunError("default port not allowed".ArgSrc(Cmd.Wsdl)))
              return;

            try {
              var s = new ChanStore(port);
              s.StartServer(port);

              conn.RunNotifySystem(string.Format("running :{0}/ChanStore", port).ArgSrc(Cmd.Wsdl));
              conn.Register(Cmd.WsdlStop, _ => {
            s.StopServer();
            conn.Reregister(Cmd.WsdlStop, null);
            conn.RunNotifySystem("stopped".ArgSrc(Cmd.Wsdl));
              });
            } catch (Exception ex) {
              ex.PipeEx(conn, Cmd.Wsdl);
            }
              });

              conn.Register(Cmd.Ip, _ => conn.RunOrDefault(Cmd.NotifySystem,
            string.Join<IPAddress>(", ", Dns.GetHostEntry("").AddressList).ArgSrc(Cmd.Ip)));

              #if DEBUG
              conn.Register("test", a => {
            conn.Run(Cmd.NotifyError, "test error".ArgSrc("err source"));
            conn.Run(Cmd.NotifyError, "test error without source");

            conn.Run(Cmd.NotifySystem, "test system".ArgSrc("system source"));
            conn.Run(Cmd.NotifySystem, "test system without source");

            conn.Run(Cmd.ReceivedMsg, "test msg".ArgSrc("msg source"));
            conn.Run(Cmd.ReceivedMsg, "test msg without source");
            conn.Run(Cmd.Help);
            conn.Run(Cmd.Chat);
              });
              #endif
        }
コード例 #4
0
        static void Main(string[] args)
        {
            while (true)
            {
                Console.Write("Your alias: ");
                _name = Console.ReadLine();

                if (string.IsNullOrEmpty(_name))
                {
                    Console.WriteLine("Your name can not be empty.");
                }
                else
                {
                    break;
                }
            }

            var choice = -1;

            while (true)
            {
                Console.Write("Are you a (1)client or a (2)server? ");

                var input = Console.ReadLine();

                if (!int.TryParse(input, out choice))
                {
                    Console.WriteLine("Invalid choice, try again.");

                    continue;
                }

                break;
            }

            switch (choice)
            {
                case 1: // Is a client
                    {
                        while (true)
                        {
                            string ip;

                            Console.Write("IP: ");
                            ip = Console.ReadLine();

                            try
                            {
                                _meTcpClient = new TcpClient(ip, 5555);
                                _me = new ChatClient(_meTcpClient, _name);

                                break;
                            }
                            catch (Exception e)
                            {
                                Console.WriteLine(e.Message);
                            }
                        }

                        new Thread(delegate()
                                   	{
                                        while (true)
                                        {
                                            _me.ReadMessage();
                                        }
                                   	}).Start();

                        while (true)
                        {
                            Console.Write("Say: ");
                            var msg = _me.Name + "\n" + Console.ReadLine();

                            var bMsg = Encoding.ASCII.GetBytes(msg);

                            _meTcpClient.GetStream().Write(bMsg, 0, bMsg.Count());
                        }

                        break;
                    }
                case 2: // Is a server
                    {
                        var server = new ChatServer(5555);
                        server.StartListening();

                        while (server.Listening)
                        {
                            server.Receive();
                            server.Send();
                        }

                        break;
                    }
            }
        }
コード例 #5
0
        static void Main()
        {
            Console.WriteLine("Application start...[ThreadID:{0}]", Thread.CurrentThread.ManagedThreadId);

            string app_identifier = "chat";
            string server_ip = "127.0.0.1";
            int server_port = 11515;
            int max_client = 100;

            ChatClient client = new ChatClient();
            client.Init(app_identifier);

            ChatServer server = new ChatServer();
            server.Init(app_identifier, server_port, max_client);
            
            while (true)
            {
                Console.Write("command> ");
                string line = Console.ReadLine();
                if (line == "quit")
                {
                    client.Close();
                    server.Stop();
                    break;
                }
                else if (line == "start server")
                {
                    server.Start();
                }
                else if (line == "connect")
                {
                    client.Connect(server_ip, server_port);
                }
                else if (line.IndexOf("login") >= 0)
                {
                    string[] token = line.Split(' ');
                    if (token.Length >= 2)
                    {
                        client.Login(token[1]);
                    }
                    else
                    {
                        Console.WriteLine("Invalid command.");
                    }
                }
                else if (line.IndexOf("logout") >= 0)
                {
                    client.Logout();
                }
                else if (line.IndexOf("send") >= 0)
                {
                    string[] token = line.Split(' ');
                    if (token.Length == 3)
                    {
                        client.Send(token[1], token[2]);
                    }
                    else
                    {
                        Console.WriteLine("Invalid command.");
                    }
                }
                else
                {
                    if (line.Length > 0 && client.IsLogin())
                    {
                        client.SendToAll(line);
                    }
                }
            }

            Console.WriteLine("Application is quitted!");
            Console.Read();
        }