Exemplo n.º 1
0
        void AsyncSendText(string ip, int port, string text)//асинхронная посылка текста
        {
            Thread t = new Thread(() =>
            {//потоковая процедура
                try
                {
                    TcpClient tcpClient      = new TcpClient(ip, port);
                    NetStreamReaderWriter ns = new NetStreamReaderWriter(tcpClient.GetStream());
                    ns.WriteLine(text);
                    //тут надо что-то сделать чтобы не закрыть соединение, пока клиент не примет сообщение
                    //пока что костыль
                    if (ns.ReadCmd().cmd != "!ok")
                    {
                        throw new Exception("В ответ получен не !ok");
                    }
                    Thread.Sleep(10000);
                }
                catch (Exception ex)
                {
                    System.Diagnostics.Debug.AutoFlush = true;
                    System.Diagnostics.Debug.WriteLine("Dispatcher. AsyncSendText. " + ex.Message);
                }
            });

            t.Start();
        }
Exemplo n.º 2
0
        void getFileList(NetStreamReaderWriter stream)
        {
            NetCommand getFileListCmd = new NetCommand()
            {
                Ip = DispatcherIP.ToString(),
                //Dns.GetHostAddresses(Dns.GetHostName())[0].ToString(),
                Port       = 501,
                sender     = "dispatcher",
                cmd        = "!getfilelist",
                parameters = ""
            };

            stream.WriteCmd(getFileListCmd);

            NetCommand ansGetFilelist = stream.ReadCmd();

            if (ansGetFilelist.cmd != "!filelist")
            {
                return;
            }
            string filesStr = ansGetFilelist.parameters;

            string[] filesList = filesStr.Split(new char[] { '|' });
            lock (Files)
            {
                foreach (string f in filesList)
                {
                    Files.Add(new FileInfo()
                    {
                        Filename = f
                    });
                }
                lock (lbFiles)
                {
                    lbFiles.Invoke(UpdateFilesListD);
                }
            }
        }
Exemplo n.º 3
0
        //void DoCommunicateWithsServer(object tcpclient)
        //{
        //    using (TcpClient tcpClient = (TcpClient)tcpclient)
        //    using (NetworkStream ns = tcpClient.GetStream())
        //    {
        //        NetStreamReaderWriter netStream = new NetStreamReaderWriter(ns);
        //        string []parameters;
        //        string cmd;
        //        string line;
        //        string param;       //если параметр 1

        //        while (tcpClient.Connected)
        //        {

        //            try
        //            {
        //                line = netStream.ReadLine();
        //                parameters = line.Split(new char[] { ' ' });
        //                cmd = parameters[0];
        //                param = line.Substring(cmd.Length);

        //                switch (cmd)
        //                {
        //                    case "!who":        //к кому я подключился?
        //                        lock (tcpclient)
        //                        {
        //                            netStream.WriteLine("dispatcher");
        //                        }
        //                        break;
        //                    case "!register":   //зарегистрируй меня
        //                        if (AddServer(parameters[1], parameters[2], Convert.ToInt32(parameters[3])))
        //                        {
        //                            lock (tcpclient)
        //                            {
        //                                netStream.WriteLine("registered");
        //                            }
        //                            //TODO
        //                            //getClientListFromServer(netStream);
        //                        }
        //                        else
        //                        {
        //                            lock (tcpclient)
        //                            {
        //                                netStream.WriteLine("notregistered");
        //                            }
        //                        }
        //                        break;
        //                    case "!getserverlist":  //дай мне список серверв сообщений
        //                        lock (tcpclient)
        //                        {
        //                            SendServerList(ns);
        //                        }
        //                        break;
        //                    case "!getclientlist":  //дай мне список клиентов
        //                        lock (tcpclient)
        //                        {
        //                            SendClientList(ns);
        //                        }
        //                        break;
        //                    case "!clientregistered":   //появился новый клиент
        //                        if( RegisterClient(param))
        //                            SendTextToAllServers(line);
        //                        break;
        //                    case "!clientunregistered":
        //                        UnregisterClient(param);
        //                        SendTextToAllServers(line);
        //                        break;
        //                    case "!getfilelist":
        //                        lock (tcpclient)
        //                        {
        //                            SendFileList(ns);
        //                        }
        //                        break;
        //                    case "!getfreefileserver":
        //                        lock (tcpclient)
        //                        {
        //                            if (FileServers.Count > 0)
        //                            {
        //                                ServerInfo fileServ;
        //                                lock (FileServers)
        //                                {
        //                                    Random r = new Random();
        //                                    int i = r.Next(0, FileServers.Count - 1);
        //                                    fileServ = FileServers[i];
        //                                }
        //                                netStream.WriteLine(String.Format("{0} {1}", fileServ.Ip, fileServ.Port));
        //                            }
        //                            else
        //                            {
        //                                netStream.WriteLine("error");
        //                            }
        //                        }
        //                        break;
        //                    case "!getfileserver":
        //                        //////////////////////////////////////TODO
        //                        break;

        //                    default:
        //                        MessageBox.Show("Dispatcher: Неизвестная команда. "+line);
        //                        break;
        //                }
        //            }
        //            catch (IOException ioex)
        //            {
        //                tbLog.Text += Environment.NewLine + ioex.Message;
        //                System.Diagnostics.Debug.WriteLine("Dispatcher :" + ioex.Message);
        //            }
        //        }
        //    }
        //}

        void DoCommunicateWithsServer_V2(object tcpclient)
        {
            using (TcpClient tcpClient = (TcpClient)tcpclient)
                using (NetworkStream ns = tcpClient.GetStream())
                {
                    ServerInfo            serverInfo = null;
                    NetStreamReaderWriter netStream  = new NetStreamReaderWriter(ns);
                    string[]   parameters;
                    NetCommand command;

                    if (tcpClient.Connected)
                    {
                        try
                        {
                            while (tcpClient.Available < 1)//пока ничего не пришло ждем
                            {
                                Thread.Sleep(200);
                                if (!tcpClient.Connected)
                                {
                                    return;
                                }
                            }
                            command    = netStream.ReadCmd();
                            parameters = command.parameters.Split(new char[] { ' ' });
                            uiWriteLog(string.Format("> cmd from msgserver {0}", command));
                            switch (command.cmd)
                            {
                            case "!who":        //к кому я подключился?
                                NetCommand dispatcherCmd = new NetCommand()
                                {
                                    Ip     = DispatcherIP.ToString(),//Dns.GetHostAddresses(Dns.GetHostName())[0].ToString(),
                                    Port   = 501,
                                    sender = "dispatcher",
                                    cmd    = "!dispatcher"
                                };
                                netStream.WriteCmd(dispatcherCmd);
                                break;

                            case "!register":   //зарегистрируй меня
                                if (AddServer(command.sender, command.Ip, command.Port, out serverInfo))
                                {
                                    NetCommand registredCmd = new NetCommand()
                                    {
                                        Ip     = DispatcherIP.ToString(),//Dns.GetHostAddresses(Dns.GetHostName())[0].ToString(),
                                        Port   = 501,
                                        sender = "dispatcher",
                                        cmd    = "!registered"
                                    };
                                    netStream.WriteCmd(registredCmd);
                                }
                                else
                                {
                                    NetCommand notRegistredCmd = new NetCommand()
                                    {
                                        Ip         = DispatcherIP.ToString(),//Dns.GetHostAddresses(Dns.GetHostName())[0].ToString(),
                                        Port       = 501,
                                        sender     = "dispatcher",
                                        cmd        = "!notregistered",
                                        parameters = ""
                                    };
                                    netStream.WriteCmd(notRegistredCmd);
                                }
                                break;

                            case "!getserverlist":  //дай мне список серверв сообщений
                                SendServerList(ns);
                                break;

                            case "!getclientlist":  //дай мне список клиентов
                                SendClientList(ns);
                                break;

                            case "!clientregistered":   //появился новый клиент
                                if (RegisterClient(command.parameters, command.Ip, command.Port))
                                {
                                    netStream.WriteCmd(CreateStandardAnswer());
                                    NetCommand c = command.Clone();//адрес отправителя уже другой
                                    c.Ip = Dns.GetHostAddresses(Dns.GetHostName())[0].ToString();
                                    SendCmdToAllServers(c);
                                }
                                break;

                            case "!clientunregistered":
                                UnregisterClient(command.parameters);
                                {
                                    netStream.WriteCmd(CreateStandardAnswer());
                                    NetCommand c = command.Clone();   //адрес отправителя уже другой
                                    c.Ip   = DispatcherIP.ToString(); //Dns.GetHostAddresses(Dns.GetHostName())[0].ToString();
                                    c.Port = 501;
                                    SendCmdToAllServers(c);
                                }

                                lock (MsgServers)
                                {
                                    //находим сервер
                                    ServerInfo server1 = MsgServers.Find((ServerInfo serv) => { return(serv.Ip == command.Ip && serv.Port == command.Port); });
                                    if (server1 != null)
                                    {
                                        server1.clientInfos.RemoveAll((ClientInfo cli) => { return(cli.ClientName == command.parameters); });
                                    }
                                }
                                break;

                            case "!getfilelist":
                                SendFileList(ns);
                                break;

                            case "!getfreefileserver":
                                if (FileServers.Count > 0)
                                {
                                    ServerInfo fileServ;
                                    lock (FileServers)
                                    {
                                        Random r = new Random();
                                        int    i = r.Next(0, FileServers.Count - 1);
                                        fileServ = FileServers[i];
                                    }
                                    NetCommand freeFileServerCmd = new NetCommand()
                                    {
                                        Ip         = DispatcherIP.ToString(),//Dns.GetHostAddresses(Dns.GetHostName())[0].ToString(),
                                        Port       = 501,
                                        sender     = "dispatcher",
                                        cmd        = "!freefileserver",
                                        parameters = String.Format("{0} {1}", fileServ.Ip, fileServ.Port)
                                    };
                                    netStream.WriteCmd(freeFileServerCmd);
                                }
                                else
                                {
                                    NetCommand errorCmd = new NetCommand()
                                    {
                                        Ip         = DispatcherIP.ToString(),//Dns.GetHostAddresses(Dns.GetHostName())[0].ToString(),
                                        Port       = 501,
                                        sender     = "dispatcher",
                                        cmd        = "!error",
                                        parameters = ""
                                    };
                                    netStream.WriteCmd(errorCmd);
                                }
                                break;

                            case "!ping":

                                if (command.sender == "msgserver")
                                {
                                    lock (MsgServers)
                                    {
                                        ServerInfo si = MsgServers.Find((ServerInfo s) => { return(s.Ip == command.Ip && s.Port == command.Port); });
                                        if (si != null)
                                        {
                                            si.lastPingTime = DateTime.Now;
                                        }
                                        else
                                        {
                                            MessageBox.Show("Пингующий сервер (СОС) не найден!", "Так быть не должно");
                                        }
                                    }
                                }
                                if (command.sender == "fileserver")
                                {
                                    lock (FileServers)
                                    {
                                        ServerInfo si = FileServers.Find((ServerInfo s) => { return(s.Ip == command.Ip && s.Port == command.Port); });
                                        if (si != null)
                                        {
                                            si.lastPingTime = DateTime.Now;
                                        }
                                        else
                                        {
                                            MessageBox.Show("Пингующий файл сервер  не найден!", "Так быть не должно");
                                        }
                                    }
                                }
                                if ((command.sender == "msgserver") || (command.sender == "fileserver"))
                                {
                                    NetCommand pongCmd = new NetCommand()
                                    {
                                        Ip         = DispatcherIP.ToString(),//Dns.GetHostAddresses(Dns.GetHostName())[0].ToString(),
                                        Port       = 501,
                                        sender     = "dispatcher",
                                        cmd        = "!pong",
                                        parameters = ""
                                    };
                                    netStream.WriteCmd(pongCmd);
                                }
                                break;

                            case "!getfileserver":
                                //////////////////////////////////////TODO
                                break;

                            default:
                                MessageBox.Show("Dispatcher: Неизвестная команда. " + command.ToString());
                                break;
                            }
                        }
                        catch (IOException ioex)
                        {
                            //tbLog.Text += Environment.NewLine + ioex.Message;
                            System.Diagnostics.Debug.WriteLine("Dispatcher :" + ioex.Message);
                        }
                    }
                }
        }
Exemplo n.º 4
0
        void DoCommunicateWithClient(object tcpclient)
        {
            uiWriteLog(string.Format("> client connecting.."));
            using (TcpClient tcpClient = (TcpClient)tcpclient)
                using (NetworkStream ns = tcpClient.GetStream())
                {
                    NetStreamReaderWriter nsrw = new NetStreamReaderWriter(ns);
                    while (tcpClient.Connected)//??
                    {
                        try
                        {
                            NetCommand command = nsrw.ReadCmd();
                            uiWriteLog(string.Format("> cmd from client {0}", command));
                            switch (command.cmd)
                            {
                            case "!who":
                                NetCommand dispatcherCmd = new NetCommand()
                                {
                                    Ip     = DispatcherIP.ToString(),//Dns.GetHostAddresses(Dns.GetHostName())[0].ToString(),
                                    Port   = 500,
                                    sender = "dispatcher",
                                    cmd    = "!dispatcher"
                                };
                                nsrw.WriteCmd(dispatcherCmd);
                                break;

                            case "!getserver":
                                ServerInfo msgServ;
                                lock (MsgServers)
                                {
                                    Random r = new Random(DateTime.Now.Millisecond);
                                    if (MsgServers.Count != 0)
                                    {
                                        int i = r.Next(0, MsgServers.Count);
                                        msgServ = MsgServers[i];
                                        NetCommand msgServerCmd = new NetCommand()
                                        {
                                            Ip         = DispatcherIP.ToString(),//Dns.GetHostAddresses(Dns.GetHostName())[0].ToString(),
                                            Port       = 500,
                                            sender     = "dispatcher",
                                            cmd        = "!msgserver",
                                            parameters = String.Format("{0} {1}", msgServ.Ip, msgServ.Port)
                                        };
                                        nsrw.WriteCmd(msgServerCmd);
                                    }
                                    else
                                    {
                                        NetCommand hasNotServerCmd = new NetCommand()
                                        {
                                            Ip         = DispatcherIP.ToString(),//Dns.GetHostAddresses(Dns.GetHostName())[0].ToString(),
                                            Port       = 500,
                                            sender     = "dispatcher",
                                            cmd        = "!hasnotserver",
                                            parameters = ""
                                        };
                                        nsrw.WriteCmd(hasNotServerCmd);
                                    }
                                }
                                break;
                            }
                        }
                        catch (IOException ioex)
                        {
                            System.Diagnostics.Debug.AutoFlush = true;
                            System.Diagnostics.Debug.WriteLine("Client. " + ioex.Message);
                            //tbLog.Text +=Environment.NewLine+ ioex.Message ;
                        }
                    }
                }
        }