Ejemplo n.º 1
0
        public Client(TcpClient client, string IP)
        {
            ClientIP = IPAddress.Parse(IP);

            ClientTCP = client;

            int timeout = 10000;

            ClientTCP.ReceiveTimeout = timeout;
            ClientTCP.SendTimeout    = timeout;

            ClientStream = client.GetStream();
            Sender       = new DataSend(this);
            Reader       = new DataRead(this);

            if (CommonDatas.NetworkSpareLevel > 100)
            {
                Checking = false;
            }
            else
            {
                Checking = true;
            }


            LifeCheckerThread = new Thread(CheckLife)
            {
                Name         = $"checker_{ClientIP.ToString()}",
                IsBackground = true,
            };

            LifeCheckerThread.Start();
        }
Ejemplo n.º 2
0
        private void InitSocket()
        {
            try
            {
                tbxLocalIpAddress.Text =
                    Regex.Replace(tbxLocalIpAddress.Text, @"[^0-9].[^0-9].[^0-9].[^0-9]", "");
                tbxPort.Text = Regex.Replace(tbxPort.Text, @"[^0-9]", "");
                if (tbxLocalIpAddress.Text == "" || tbxPort.Text == "")
                {
                    MessageBox.Show("Local IP Address 또는 Port 번호가 올바르지 않습니다.");
                    throw new Exception();
                }
                TcpListner = new TcpListener(IPAddress.Parse(tbxLocalIpAddress.Text.Trim()), Int32.Parse(tbxPort.Text));
                TcpClient  = default(TcpClient);
                TcpListner.Start();
                DisplayText(">> server Started");
                while (true)
                {
                    try
                    {
                        TcpClient = TcpListner.AcceptTcpClient();

                        NetworkStream stream  = TcpClient.GetStream();
                        byte[]        buffer  = new byte[1024];
                        int           bytes   = stream.Read(buffer, 0, buffer.Length);
                        string        channel = Encoding.Unicode.GetString(buffer, 0, bytes);
                        channel = channel.Split('$')[0];

                        this.Invoke(new DeligateGetClientIP(GetClientIP), channel);

                        ClientList.Add(TcpClient, channel);

                        IpPoint  = (IPEndPoint)TcpClient.Client.RemoteEndPoint;
                        ClientIP = IpPoint.Address + ":" + IpPoint.Port;
                        ClientInfoList.Add(ClientIP.ToString());
                        SendMessageAll(ClientIP + "/ 님이 연결되었습니다.", channel, false);

                        HandleClient handle = new HandleClient();
                        handle.OnReceived     += new HandleClient.MessageDisplayHandler(OnReceived);
                        handle.OnDisconnected += new HandleClient.DisconnectedHandler(HandlerClientsOnDisconnected);
                        handle.StartClient(TcpClient, ClientList);
                    }
                    catch
                    {
                        throw new SocketException();
                    }
                }
            }
            catch (SocketException ex)
            {
                this.Invoke(new DeligateDisconnect(Disconnect));
            }
            catch (Exception ex)
            { }
            finally
            {
                this.Invoke(new DeligateButtonChange(ButtonStatusChange));
            }
        }
        void SmoothStreamingSourceChanged(string url)
        {
            Uri currentStreamUri = new Uri(url, UriKind.Absolute);

            IsEdgeServerComplete = false;
            EdgeServer           = EdgeServerDataClient.IpNA; // clear the current edge server
            ClientIP             = EdgeServerDataClient.IpNA;

            if (Configuration.EdgeServerRuleCollection != null)
            {
                EdgeServerRules addressRules = Configuration.EdgeServerRuleCollection.FirstOrDefault(ai => ai.Domain != null && currentStreamUri.Host.EndsWith(ai.Domain, StringComparison.OrdinalIgnoreCase));
                // fallback on the address rules without a domain
                if (addressRules == null)
                {
                    addressRules = Configuration.EdgeServerRuleCollection.FirstOrDefault(ai => ai.Domain == null);
                }
                try
                {
                    if (addressRules != null)
                    {
                        EdgeServerDataClient edgeServerDataClient = new EdgeServerDataClient();
                        edgeServerDataClient.GetEdgeServerCompleted += (s, e) =>
                        {
                            // warning: this can come back after we've shut down, checking for the mediaelement is a good way to ensure we're still supposed to be tracking
                            if (mediaElement != null)
                            {
                                if (e.Result != null)
                                {
                                    EdgeServer = e.Result.EdgeServer;
                                    ClientIP   = e.Result.ClientIP;
                                }
                                FinishSettingEdgeServer();

                                SmoothStreamingEvent entry = new SmoothStreamingEvent();
                                entry.EventType = EventType.AddressInfo;
                                entry.Data1     = ClientIP.ToString();
                                entry.Data2     = EdgeServer;
                                Enqueue(entry);
                            }
                        };
                        edgeServerDataClient.GetEdgeServerAsync(addressRules, currentStreamUri);
                    }
                    else
                    {
                        FinishSettingEdgeServer();
                    }
                }
                catch
                {
                    FinishSettingEdgeServer();
                }
            }
            else
            {
                FinishSettingEdgeServer();
            }
        }
Ejemplo n.º 4
0
        private void SetMetaData(Command c)
        {
            switch (c.CommandType)
            {
            case (type.ClientLogin):
                c.Meta = ClientIP.ToString() + ":" + netName;
                break;

            case (type.PCLockTimer):
            case (type.PCLogOFFTimer):
            case (type.PCRestartTimer):
            case (type.PCShutDownTimer):
            case (type.UserExitTimer):
                c.Meta = "60000";
                break;

            default:
                c.Meta = "\n";
                break;
            }
        }
Ejemplo n.º 5
0
        private void connector_DoWork(object sender, DoWorkEventArgs e)
        {
            try
            {
                client = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
                client.Connect(endpoint);
                e.Result  = true;
                netStream = new NetworkStream(client);
                receiver  = new BackgroundWorker();
                receiver.WorkerSupportsCancellation = true;
                receiver.DoWork += new DoWorkEventHandler(StartReceive);
                receiver.RunWorkerAsync();

                //send a notification that this client has connnected
                Command massMsg = new Command(type.ClientLogin, IPAddress.Broadcast, ClientIP.ToString() + ":" + netName);
                SendCommand(massMsg);
            }
            catch
            {
                e.Result = false;
            }
        }
Ejemplo n.º 6
0
        public void Disconnect()
        {
            //már nem küld semmi adatot
            SendingDatas = false;

            //a kliens kiszedése a kliens listából
            ClientMethods.RemoveClient(this);

            try
            {
                //a kapcsolat bezárása
                ClientTCP.Close();
                //a stream bezárása
                ClientStream.Close();
            }
            catch (Exception)
            {
            }

            Checking = false;

            DisconnectOperations.SetKilokosOffline(ClientIP.ToString());
        }
Ejemplo n.º 7
0
        private void InitSocket()
        {
            try
            {
                tbxLocalIpAddress.Text =
                    Regex.Replace(tbxLocalIpAddress.Text, @"[^0-9].[^0-9].[^0-9].[^0-9]", "");
                tbxPort.Text = Regex.Replace(tbxPort.Text, @"[^0-9]", "");
                if (tbxLocalIpAddress.Text == "" || tbxPort.Text == "")
                {
                    MessageBox.Show("Local IP Address 또는 Port 번호가 올바르지 않습니다.");
                    throw new Exception();
                }
                TcpListner = new TcpListener(IPAddress.Parse(tbxLocalIpAddress.Text.Trim()), Int32.Parse(tbxPort.Text));
                TcpClient  = default(TcpClient);
                TcpListner.Start();
                DisplayText(">> server Started");
                while (true)
                {
                    try
                    {
                        TcpClient = TcpListner.AcceptTcpClient();

                        NetworkStream stream = TcpClient.GetStream();

                        stream = TcpClient.GetStream();//acc.Receive(sizeBuf, 0, sizeBuf.Length, 0);

                        byte[] sizeBuf = new byte[TcpClient.ReceiveBufferSize];
                        stream.Read(sizeBuf, 0, (int)TcpClient.ReceiveBufferSize);
                        int size = BitConverter.ToInt32(sizeBuf, 0);

                        MemoryStream ms = new MemoryStream();

                        while (size > 0)
                        {
                            byte[] buffer;
                            if (size < TcpClient.ReceiveBufferSize) //acc.ReceiveBufferSize)
                            {
                                buffer = new byte[size];
                            }
                            else
                            {
                                buffer = new byte[TcpClient.ReceiveBufferSize];
                            }

                            int rec = stream.Read(buffer, 0, buffer.Length);

                            size -= rec;
                            ms.Write(buffer, 0, buffer.Length);
                        }
                        ms.Close();

                        byte[] data = ms.ToArray();

                        ms.Dispose();

                        string channel = Encoding.UTF8.GetString(data);


                        this.Invoke(new DeligateGetClientIP(GetClientIP), channel);

                        ClientList.Add(TcpClient, channel);

                        IpPoint  = (IPEndPoint)TcpClient.Client.RemoteEndPoint;
                        ClientIP = IpPoint.Address + ":" + IpPoint.Port;
                        ClientInfoList.Add(ClientIP.ToString());

                        SendMessageAll(ClientIP + "/ 님이 연결되었습니다.", channel, true);

                        HandleClient handle = new HandleClient();
                        handle.OnReceived     += new HandleClient.MessageDisplayHandler(OnReceived);
                        handle.OnDisconnected += new HandleClient.DisconnectedHandler(HandlerClientsOnDisconnected);
                        handle.StartClient(TcpClient, ClientList);
                    }
                    catch
                    {
                        throw new SocketException();
                    }
                }
            }
            catch (SocketException ex)
            {
                this.Invoke(new DeligateDisconnect(Disconnect));
                ServerEvent.ErrorLog("InitSocket", ex.Message);
            }
            catch (Exception ex)
            {
                ServerEvent.ErrorLog("InitSocket", ex.Message);
            }
            finally
            {
                this.Invoke(new DeligateButtonChange(ButtonStatusChange));
            }
        }
Ejemplo n.º 8
0
        public void ProcessRequest()
        {
            IPEndPoint EndPoint = Client.Client.RemoteEndPoint as IPEndPoint;

            ClientIP   = EndPoint.Address;
            ClientPort = (ushort)EndPoint.Port;
            ClientId   = ClientIP.ToString() + ":" + ClientPort;

            if (Client.Connected)
            {
                var before = DateTime.Now;
                while (!Stream.DataAvailable)
                {
                    Thread.Sleep(20);
                    if ((DateTime.Now - before).Milliseconds > 1000)
                    {
                        Console.WriteLine("{0} - No data sent within 1s", ClientId);
                        Client.Close();
                        return;
                    }
                }
            }
            else
            {
                return;
            }

            using (var ms = new MemoryStream())
            {
                bool     prevN   = false;
                int      prevoff = 0;
                int      os      = 0;
                DateTime before  = DateTime.Now;
                try
                {
                    while (true)
                    {
                        if (Stream.DataAvailable)
                        {
                            if (os > HeaderIngestBuffer.Length)
                            {
                                E400();
                                Console.WriteLine("Request header exceeded buffer size!");
                                return;
                            }
                            before = DateTime.Now;
                            HeaderIngestBuffer[os] = (byte)Stream.ReadByte();

                            if (HeaderIngestBuffer[os] == 13)
                            {
                                os++;
                                continue;
                            }
                            if (HeaderIngestBuffer[os] == 10)
                            {
                                if (prevN)
                                {
                                    break;
                                }
                                prevN = true;
                                RqHeaders.Add(Encoding.UTF8.GetString(HeaderIngestBuffer, prevoff, os - prevoff).Trim());
                                prevoff = os;
                            }
                            else
                            {
                                prevN = false;
                            }
                            os++;
                        }
                        else
                        {
                            Thread.Sleep(20);
                            if ((DateTime.Now - before).TotalMilliseconds > 500)
                            {
                                Console.WriteLine("{0} - No data sent for 500ms", ClientId);
                                Client.Close();
                                return;
                            }
                        }

                        if ((DateTime.Now - before).TotalMilliseconds > 1000)
                        {
                            Console.WriteLine("{0} - HTTP Header not sent within 1s", ClientId);
                            Client.Close();
                            return;
                        }
                    }

                    ms.Write(HeaderIngestBuffer, 0, os + 1);
                }
                catch                // (Exception E)
                {
                    Console.WriteLine("{0} - Exception while receiving request header", ClientId);
                    return;
                }
                Request = ms.ToArray();
            }

            int TotalData = 0;

            ModifiedRequest = new StringBuilder(Request.Length);
            //Console.WriteLine(RqHeaders[0]);
            for (int i = 0; i < RqHeaders.Count; i++)
            {
                string s = RqHeaders[i];

                Match N = Regex.Match(s, @"^Content-Length:\s+(\d+)$", RegexOptions.IgnoreCase);
                if (N.Success)
                {
                    ThroughPutContentLength = long.Parse(N.Groups[1].Value);
                }

                N = Regex.Match(s, @"^Connection:\s+[^\s]+$", RegexOptions.IgnoreCase);
                if (N.Success)
                {
                    RqHeaders[i] = "Connection: close";
                }

                N = Regex.Match(s, @"^(Host):\s+([^\s]+)$", RegexOptions.IgnoreCase);
                if (N.Success)
                {
                    Host         = N.Groups[2].Value;
                    RqHeaders[i] = string.Format("{0}: {1}", ReplaceWith, Host);
                    HostStart    = TotalData;
                    HostLength   = RqHeaders[i].Length;
                }

                TotalData += RqHeaders[i].Length + 2;
                ModifiedRequest.Append(RqHeaders[i]);
                ModifiedRequest.Append("\r\n");
            }
            ModifiedRequest.Append("\r\n");

            //Console.WriteLine("Header size after upgrade: " + ModifiedRequest.Length);

            if (Host == null)
            {
                E400();
                return;
            }

            if ((HostIP = DNSManager.GetIP(Host)) == null)
            {
                Console.WriteLine("Host {0} not found!", Host);
                E404();
                return;
            }

            Request = Encoding.UTF8.GetBytes(ModifiedRequest.ToString());

            //Console.WriteLine("Alleged host header: \"{0}\"", Encoding.UTF8.GetString(Request, HostStart, HostLength).Replace("\r", "\\r").Replace("\n", "\\n"));
            //Console.WriteLine("Byte at host start index: {0}", Encoding.UTF8.GetString(new byte[1] { Request[HostStart] }).Replace("\r", "\\r").Replace("\n", "\\n"));
            //Console.WriteLine("Byte at host end index: {0}", Encoding.UTF8.GetString(new byte[1] { Request[HostStart + HostLength - 1] }).Replace("\r", "\\r").Replace("\n", "\\n"));

            var Target = new TcpClient();

            try
            {
                Target.Connect(HostIP, 80);
            }
            catch
            {
                E503();
                return;
            }

            var TgStream = Target.GetStream();

            try
            {
                int TotalSent = HostStart;
                TgStream.Write(Request, 0, HostStart);
                bool SendNotWrite = false;
                while (TotalSent < HostStart + HostLength)
                {
                    if (!SendNotWrite)
                    {
                        TgStream.Write(Request, TotalSent, BreakEvery);
                    }
                    else
                    {
                        Target.Client.Send(Request, TotalSent, BreakEvery, SocketFlags.None);
                    }
                    TotalSent   += BreakEvery;
                    SendNotWrite = !SendNotWrite;
                }
                TgStream.Write(Request, TotalSent, Request.Length - TotalSent);
                TotalSent += Request.Length - TotalSent;
                //Console.WriteLine("Send valid: {0}", TotalSent == Request.Length);

                if (ThroughPutContentLength != 0)
                {
                    ThroughPutBuffer = new byte[ThroughPutBufferSize];
                    long bytesWritten = 0;
                    int  bytesRead    = 0;
                    while (Client.Connected && Target.Connected && bytesWritten < ThroughPutContentLength)
                    {
                        bytesRead = Stream.Read(ThroughPutBuffer, 0, ThroughPutBuffer.Length);
                        TgStream.Write(ThroughPutBuffer, 0, bytesRead);
                        bytesWritten += bytesRead;
                    }
                }
            }
            catch            // (Exception E)
            {
                Console.WriteLine("{0} - Exception while attempting to send request", Host);
                Target.Close();
                E400();
                return;
            }

            if (Target.Connected)
            {
                var before = DateTime.Now;
                while (!TgStream.DataAvailable)
                {
                    Thread.Sleep(20);
                    if ((DateTime.Now - before).Milliseconds > 1000)
                    {
                        Console.WriteLine("{0} - No response sent in 1s", Host);
                        E503();
                        Target.Close();
                        return;
                    }
                }
            }
            else
            {
                Console.WriteLine("{0} - Target disconnected before answering response", Host);
                E503();
                Target.Close();
                return;
            }

            try
            {
                bool     prevN   = false;
                int      prevoff = 0;
                int      os      = 0;
                DateTime before  = DateTime.Now;
                while (true)
                {
                    if (TgStream.DataAvailable)
                    {
                        if (os > DownloadBuffer.Length)
                        {
                            E503();
                            Target.Close();
                            Console.WriteLine("{0} - Request header exceeded buffer size!", Host);
                            return;
                        }
                        before             = DateTime.Now;
                        DownloadBuffer[os] = (byte)TgStream.ReadByte();
                        Stream.WriteByte(DownloadBuffer[os]);
                        if (DownloadBuffer[os] == 13)
                        {
                            os++;
                            continue;
                        }
                        if (DownloadBuffer[os] == 10)
                        {
                            if (prevN)
                            {
                                break;
                            }
                            prevN = true;
                            RcvHeaders.Add(Encoding.UTF8.GetString(DownloadBuffer, prevoff, os - prevoff).Trim());
                            prevoff = os;
                        }
                        else
                        {
                            prevN = false;
                        }
                        os++;
                    }
                    else
                    {
                        Thread.Sleep(20);
                        if ((DateTime.Now - before).TotalMilliseconds > 500)
                        {
                            Console.WriteLine("{0} - Response end not sent within 500 ms", Host);
                            Client.Close();
                            Target.Close();
                            return;
                        }
                    }
                }

                foreach (string s in RcvHeaders)
                {
                    Match N = Regex.Match(s, @"^\n?Content-Length:\s+(\d+)\r?\n?$", RegexOptions.IgnoreCase);
                    if (N.Success)
                    {
                        DownloadContentLength = long.Parse(N.Groups[1].Value);
                    }
                }

                int bytesRead  = 0;
                int bytesTotal = 0;
                if (DownloadContentLength == 0)
                {
                    while (Client.Connected && Target.Connected && TgStream.DataAvailable)
                    {
                        Stream.Write(DownloadBuffer, 0, TgStream.Read(DownloadBuffer, 0, DownloadBuffer.Length));
                        Thread.Sleep(50);
                    }
                }
                else
                {
                    while (Client.Connected && Target.Connected && bytesTotal < DownloadContentLength)
                    {
                        bytesRead   = TgStream.Read(DownloadBuffer, 0, DownloadBuffer.Length);
                        bytesTotal += bytesRead;
                        Stream.Write(DownloadBuffer, 0, bytesRead);
                    }
                }
            }
            catch            // (Exception E)
            {
#if DEBUG
                Console.WriteLine("{0} >>> {1} - Exception while handling response", ClientId, Host);
#endif
            }

            Client.Close();
            Target.Close();
            return;
        }