Exemple #1
0
        public void Listen(int u)
        {
            try
            {
                tcpListener = new TcpListenerEx(IPAddress.Parse(IP), Port);
                tcpListener.Start();
                Debug.WriteLine("Сервер запущен.");

                while (true)
                {
                    TcpClient tcpClient = tcpListener.AcceptTcpClient();

                    ClientObject clientObject = new ClientObject(tcpClient, this);
                    //clientObject.setReceiveOut(receiveOut);
                    //clientObject.setId(clientObject.GetMessage());
                    Thread clientThread = new Thread(new ThreadStart(clientObject.Process));
                    clientThread.Start();
                }
            }
            catch (Exception ex)
            {
                Debug.WriteLine(ex.Message);
                Disconnect();
            }
        }
        private void backgroundWorker1_DoWork(object sender, System.ComponentModel.DoWorkEventArgs e)
        {
            IPEndPoint    ep       = e.Argument as IPEndPoint;
            TcpListenerEx listener = new TcpListenerEx(ep);

            if (!listener.Active)
            {
                listener.Start();
            }
            while (true)
            {
                try
                {
                    const int byteSize = 1024 * 1024;
                    byte[]    message  = new byte[byteSize];
                    using (var s = listener.AcceptTcpClient())
                    {
                        s.GetStream().Read(message, 0, byteSize);    //obtaining network stream and receiving data through .Read()
                        message = cleanMessage(message);
                        string g = System.Text.Encoding.UTF8.GetString(message);
                        backgroundWorker1.ReportProgress(0, g);
                    }
                }
                catch
                {
                }
                finally
                {
                    listener.Stop();
                }
            }
        }
 public void Start()
 {
     listener.Start();
     timerCallAcceptClients = new Timer(new TimerCallback((state) =>
     {
         AcceptClientAsync();
     }), null, 0, (int)TimeSpan.FromSeconds(1).TotalMilliseconds);
 }
Exemple #4
0
        public void StartListeningToPort(int port)
        {
            new Thread(() =>
            {
                Console.Out.WriteLine(" [TCP] SERVER IS RUNNING");

                var tcpListener = new TcpListenerEx(
                    localaddr: IPAddress.Parse(Localhost),
                    port: TcpServerListeningPort);

                try
                {
                    tcpListener.Start();

                    Console.WriteLine(" [TCP] The local End point is  :" + tcpListener.LocalEndpoint);
                    Console.WriteLine(" [TCP] Waiting for a connection.....");
                    Console.Out.WriteLine();

                    while (true) // is serving continuously
                    {
                        Socket workerTcpSocket = tcpListener.AcceptSocket();

                        Console.WriteLine($" [TCP] Connection accepted from: {{ {workerTcpSocket.RemoteEndPoint} }}");
                        Console.WriteLine($" [TCP] SoketWorker is bound to: {{ {workerTcpSocket.LocalEndPoint} }}");

                        TcpServerWorker.Instance
                        .Init(workerTcpSocket, tcpListener)
                        .StartWorking();

                        //// TODO Unchecked modification
                        //if (tcpListener.Inactive)
                        //{
                        //    tcpListener.Stop();
                        //}
                    }
                }
                catch (Exception e)
                {
                    Console.Out.WriteLine("[TCP] Grave error occured. Searver is dead.");
                    Console.Out.WriteLine($"e = {e.Message}");
                    Debug.WriteLine("[TCP] Grave error occured. Searver is dead.");
                    Debug.WriteLine($"e = {e.Message}");
                    Console.Out.WriteLine("[TCP] PRESS ANY KEY TO QUIT");
                    Console.ReadLine();

                    //throw; // TODO Unchecked modification
                }
                finally
                {
                    if (tcpListener.Active)
                    {
                        tcpListener.Stop();
                    }
                }
            }).Start();
        }
Exemple #5
0
 public void Start()
 {
     if (_listener.Active)
     {
         return;
     }
     _listener.Start();
     _worker.RunWorkerAsync();
     Message = "Start listening: " + _listener.Server.LocalEndPoint;
 }
Exemple #6
0
        /// <summary>
        /// Begins running the proxy on a randomly chosen port.
        /// </summary>
        public static void Initiate()
        {
            Terminate();

            IsRunning = true;
            _listener.Start();
            Port = ((IPEndPoint)_listener.LocalEndpoint).Port;

            NativeMethods.EnableProxy(Port);
            _listener.BeginAcceptSocket(RequestIntercepted, null);
        }
Exemple #7
0
        public static void Main(string[] args)
        {
            #region 加载控制台事件钩子

            if (SetConsoleCtrlHandler(new ConsoleCtrlDelegate(HandleConsole), true))
            {
                LogUtils.Info("注册控制台事件成功");
            }
            else
            {
                LogUtils.Warn("注册控制台事件失败");
            }
            #endregion

            #region 加载配置信息
            LogUtils.Info("开始加载配置文件");

            ServerConfig.I = ServerConfig.Load(ConfigUtils.GetString("ServerConfigFile", "ServerConfig.xml"));
            if (ServerConfig.I == null)
            {
                LogUtils.Error("加载配置文件失败,程序退出");
                Thread.Sleep(1000);
                return;
            }
            #endregion

            #region 启用服务器

            LogUtils.Info("开始启动服务器,");
            TcpListenerEx serverListener = new TcpListenerEx();
            if (serverListener.Start())
            {
                LogUtils.Info("启动服务器成功");
            }
            else
            {
                LogUtils.Error("启动服务器失败,程序退出");
                Thread.Sleep(1000);
                return;
            }
            #endregion

            #region 处理命令行输入
            #endregion

            Console.ReadLine();
        }
        private void StartReceive(BindInformation bindInformation, Action <IPortListener, byte[]> messageReceived)
        {
            if (bindInformation == null)
            {
                return;
            }

            var endPoint = new IPEndPoint(IPAddress.Parse(bindInformation.Address), bindInformation.Port);

            _listener = new TcpListenerEx(endPoint);
            _listener.Start();
            Console.WriteLine($"Started Listening : {bindInformation.Address}:{bindInformation.Port}");
            var buffer = new byte[8192];

            //Gelen bağlantıyı kabul etmek için asenkron bir işlem başlatır.
            _listener.BeginAcceptSocket(OnAccept, Tuple.Create(_listener, messageReceived));
            Console.WriteLine("Started Accepting Clients");
        }
Exemple #9
0
        public void StartListening(int tcpServingPort, Action <Socket> handleRequestAction)
        {
            var tcpListener = new TcpListenerEx(IPAddress.Any, tcpServingPort);

            Console.Out.WriteLine($"TcpListener is active? [ {tcpListener.Active} ]");

            try
            {
                tcpListener.Start();
                Console.Out.WriteLine($"TcpListener is active? [ {tcpListener.Active} ]");
                Console.Out.WriteLine($"Listening at {IPAddress.Any}:{tcpServingPort}");

                Console.WriteLine(" [TCP] The local End point is  :" + tcpListener.LocalEndpoint);
                Console.WriteLine(" [TCP] Waiting for a connection.....\n");

                while (true) // is serving continuously
                {
                    Socket workerSoket = tcpListener.AcceptSocket();

                    Console.WriteLine($" [TCP] Connection accepted from: {{ {workerSoket.RemoteEndPoint} }}");
                    Console.WriteLine($" [TCP] SoketWorker is bound to: {{ {workerSoket.LocalEndPoint} }}");

                    new Thread(() => handleRequestAction(workerSoket)).Start();
                }
            }
            catch (Exception e)
            {
                Console.Out.WriteLine("[TCP] Grave error occurred. Server is dead.");
                Console.Out.WriteLine($"e = {e.Message}");
                Debug.WriteLine("[TCP] Grave error occurred. Server is dead.");
                Debug.WriteLine($"e = {e.Message}");
                Console.Out.WriteLine("[TCP] PRESS ANY KEY TO QUIT");
                Console.ReadLine();
            }
            finally
            {
                if (tcpListener.Active)
                {
                    tcpListener.Stop();
                }
            }
        }
Exemple #10
0
        public void Listen()
        {
            try
            {
                tcpListener = new TcpListenerEx(IPAddress.Parse(IP), Port);
                tcpListener.Start();
                Debug.WriteLine("Сервер запущен.");

                while (true)
                {
                    TcpClient tcpClient = tcpListener.AcceptTcpClient();

                    ClientObject clientObject = new ClientObject(tcpClient, this);
                    AddConnection(clientObject);
                }
            }
            catch (Exception ex)
            {
                Debug.WriteLine(ex.Message);
                Disconnect();
            }
        }
Exemple #11
0
        private void StartListening()
        {
            try
            {
                listener = new TcpListenerEx(localEndPoint);
                listener.Start();
                Runner.Primary(() => OnStartListening.Invoke());

                // An incoming connection needs to be processed.
                client = listener.AcceptTcpClient();
                client.ReceiveBufferSize = Int32.MaxValue;
                networkStream            = client.GetStream();

                AcceptConnection();
            }
            catch (Exception e)
            {
                Console.WriteLine(e.ToString() + "Line 79");
            }


            Console.WriteLine("\nPress ENTER to continue...");
            //Console.Read();
        }
Exemple #12
0
        private void ReceiveDiscoveryResponseMessages(int discoveryTimeout)
        {
            Thread thread = new Thread(() =>
            {
                //Console.Out.WriteLine("Run the Receive Discovery Response SERVICE");
                Console.Out.WriteLine($"DISCOVERY SERVICE is running [ timeout: {discoveryTimeout} sec. ]");
                IPAddress ipAddress = Dns.GetHostAddresses(Dns.GetHostName()).FirstOrDefault();
#if DEBUG
                Console.Out.WriteLine($"Listening to {IPAddress.Any}:{_discoveryResponsePort}");
#endif

                var tcpListener = new TcpListenerEx(IPAddress.Any, _discoveryResponsePort);

                try
                {
                    tcpListener.Start();
#if DEBUG
                    Console.Out.WriteLine($" [TCP] The socket is active? {tcpListener.Active}");
                    Console.WriteLine(" [TCP] The local End point is  :" + tcpListener.LocalEndpoint);
                    Console.WriteLine(" [TCP] Waiting for a connection.....\n");
#endif

                    TimeSpan timeoutTimeSpan    = TimeSpan.FromSeconds(discoveryTimeout);
                    DateTime listeningStartTime = DateTime.Now;

                    // is serving continuously while timeout isn't reached
                    while (_discoveryIsActive &&
                           DateTime.Now.Subtract(listeningStartTime) < timeoutTimeSpan)
                    {
#if DEBUG
                        Console.Out.WriteLine("Before accepting....");
#endif

                        Socket workerSoket = tcpListener.AcceptSocket();

#if DEBUG
                        Console.WriteLine($" [TCP] Connection accepted from: {{ {workerSoket.RemoteEndPoint} }}");
                        Console.WriteLine($" [TCP] SocketWorker is bound to: {{ {workerSoket.LocalEndPoint} }}");
#endif
                        new Thread(() =>
                        {
#if DEBUG
                            Console.Out.WriteLine(
                                $"[TCP] >> SERVER WORKER IS TALKING TO {workerSoket.RemoteEndPoint}");
#endif

                            if (tcpListener.Inactive)
                            {
#if DEBUG
                                Console.Out.WriteLine("[TCP] >> DISCOVERY LISTENER IS DOWN. Closing connection...");
#endif
                                return;
                            }

                            byte[] buffer = new byte[Common.UnicastBufferSize];

                            int receivedBytes = workerSoket.Receive(buffer);

                            workerSoket.Close();

                            byte[] data = buffer.Take(receivedBytes).ToArray();

                            string xmlData = data.ToUtf8String();

#if DEBUG
                            Console.Out.WriteLine(xmlData);
#endif

                            DiscoveryResponseMessage responseMessage = xmlData
                                                                       .DeserializeTo <DiscoveryResponseMessage>();

#if DEBUG
                            Console.Out.WriteLine(" [TCP]   >> DISCOVERY LISTENER has finished job");
#endif

                            _discoveryResponseMessages.Add(responseMessage);
                        }).Start();
                    }
                }
                catch (Exception)
                {
                    Console.Out.WriteLine("DISCOVERY SERVICE has crashed.");
                }
                finally
                {
                    if (tcpListener.Active)
                    {
                        tcpListener.Stop();
                    }
                }
            });

            thread.Start();
        }