Пример #1
0
 public Listener(
     int port,
     int timeout,
     bool useIPv6,
     PropertyChangedWithValueEventHandler propertyChangedHandler = null,
     MessageReceivedEventHandler messageReceivedEventHandler     = null
     )
 {
     Port    = port;
     Timeout = timeout;
     if (propertyChangedHandler != null)
     {
         _propertyChangedHandler        = propertyChangedHandler;
         this.PropertyChangedWithValue += propertyChangedHandler;
     }
     if (messageReceivedEventHandler != null)
     {
         _messageReceivedEventHandler = messageReceivedEventHandler;
         this.MessageReceived        += messageReceivedEventHandler;
     }
     _listener = new TcpListenerEx(
         (useIPv6 ?
          IPAddress.IPv6Any :
          IPAddress.Any),
         Port
         );
     if (useIPv6)
     {
         _listener.Server.SetSocketOption(SocketOptionLevel.IPv6, SocketOptionName.IPv6Only, 0);
     }
     _worker = CreateWorker();
 }
        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();
                }
            }
        }
Пример #3
0
        static Eavesdropper()
        {
            _headerPairSplit = new[] { ':', ' ' };
            _commandSplit    = new[] { '\r', '\n' };

            _listener = new TcpListenerEx(IPAddress.Any, 0);
        }
Пример #4
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();
            }
        }
Пример #5
0
        public void Connect(bool hostsWrite, string host, int port)
        {
            Host = host;
            Port = port;
            ResetHost();

            Addresses = Dns.GetHostAddresses(host)
                        .Select(ip => ip.ToString()).ToArray();

            if (hostsWrite)
            {
                EnforceHost();
                string[] lines = File.ReadAllLines(_hostsPath);
                if (!Array.Exists(lines, ip => Addresses.Contains(ip)))
                {
                    List <string> gameIPs = Addresses.ToList();

                    if (!gameIPs.Contains(Host))
                    {
                        gameIPs.Add(Host);
                    }

                    string mapping = string.Format("127.0.0.1\t\t{{0}}\t\t#{0}[{{1}}/{1}]", Host, gameIPs.Count);
                    File.AppendAllLines(_hostsPath, gameIPs.Select(ip => string.Format(mapping, ip, gameIPs.IndexOf(ip) + 1)));
                }
            }

            (_htcpExt = new TcpListenerEx(IPAddress.Any, Port)).Start();
            _htcpExt.BeginAcceptSocket(SocketAccepted, null);
            _disconnectAllowed = true;
        }
Пример #6
0
        private void DataFromClient(IAsyncResult iAr)
        {
            try
            {
                if (_clientS == null)
                {
                    return;
                }
                int length = _clientS.EndReceive(iAr);
                if (length < 1)
                {
                    Disconnect(); return;
                }

                byte[] data = ByteUtils.CopyBlock(_clientB, 0, length);
                #region Official Socket Check
                if (!_hasOfficialSocket)
                {
                    bool isModern = Modern.DecypherShort(data, 4) == 4000;
                    if (_hasOfficialSocket = (isModern || Ancient.DecypherShort(data, 3) == 206))
                    {
                        ResetHost();

                        _htcpExt.Stop();
                        _htcpExt = null;

                        Protocol = isModern ? HProtocol.Modern : HProtocol.Ancient;
                        OnConnected(EventArgs.Empty);
                    }
                    else
                    {
                        SendToServer(data);
                        return;
                    }
                }
                #endregion
                #region Decrypt/Split
                if (ClientDecrypt != null)
                {
                    ClientDecrypt.Parse(data);
                }

                if (_toServerS == 3 && Protocol == HProtocol.Modern)
                {
                    int dLength = data.Length >= 6 ? Modern.DecypherInt(data) : 0;
                    RequestEncrypted = (dLength != data.Length - 4);
                }

                byte[][] chunks = RequestEncrypted ? new[] { data } : ByteUtils.Split(ref _clientC, data, HDestination.Server, Protocol);
                #endregion

                foreach (byte[] chunk in chunks)
                {
                    ProcessOutgoing(chunk);
                }

                ReadClientData();
            }
            catch { Disconnect(); }
        }
Пример #7
0
        public void Connect(bool loopback = false)
        {
            if (loopback)
            {
                if (!File.Exists(HostsPath))
                {
                    File.Create(HostsPath).Close();
                }

                string[] hostsL = File.ReadAllLines(HostsPath);
                if (!Array.Exists(hostsL, ip => Addresses.Contains(ip)))
                {
                    List <string> gameIPs = Addresses.ToList(); if (!gameIPs.Contains(Host))
                    {
                        gameIPs.Add(Host);
                    }
                    string mapping = string.Format("127.0.0.1\t\t{{0}}\t\t#{0}[{{1}}/{1}]", Host, gameIPs.Count);
                    File.AppendAllLines(HostsPath, gameIPs.Select(ip => string.Format(mapping, ip, gameIPs.IndexOf(ip) + 1)));
                }
            }

            (_htcpExt = new TcpListenerEx(IPAddress.Any, Port)).Start();
            _htcpExt.BeginAcceptSocket(SocketAccepted, null);
            _disconnectAllowed = true;
        }
Пример #8
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();
        }
Пример #9
0
        private void DataFromClient(IAsyncResult iAr)
        {
            try
            {
                if (_clientS == null)
                {
                    return;
                }
                int length = _clientS.EndReceive(iAr);
                if (length < 1)
                {
                    Disconnect(); return;
                }

                byte[] data = new byte[length];
                Buffer.BlockCopy(_clientB, 0, data, 0, length);

                if (!_hasOfficialSocket)
                {
                    if (_hasOfficialSocket = (BigEndian.DecypherShort(data, 4) == 4000))
                    {
                        ResetHost();
                        _htcpExt.Stop();
                        _htcpExt = null;

                        OnConnected(EventArgs.Empty);
                    }
                    else
                    {
                        SendToServer(data);
                        return;
                    }
                }

                if (OutgoingDecrypt != null)
                {
                    OutgoingDecrypt.Parse(data);
                }

                if (_toServerS == 3)
                {
                    int dLength = data.Length >= 6 ? BigEndian.DecypherInt(data) : 0;
                    IsOutgoingEncrypted = (dLength != data.Length - 4);
                }
                IList <byte[]> chunks = ByteUtils.Split(ref _clientC, data, !IsOutgoingEncrypted);

                foreach (byte[] chunk in chunks)
                {
                    ProcessOutgoing(chunk);
                }

                ReadClientData();
            }
            catch { Disconnect(); }
        }
Пример #10
0
        public void Disconnect()
        {
            if (!_disconnectAllowed)
            {
                return;
            }
            _disconnectAllowed = false;

            lock (_disconnectLock)
            {
                if (_clientS != null)
                {
                    _clientS.Shutdown(SocketShutdown.Both);
                    _clientS.Close();
                    _clientS = null;
                }
                if (_serverS != null)
                {
                    _serverS.Shutdown(SocketShutdown.Both);
                    _serverS.Close();
                    _serverS = null;
                }
                ResetHost();
                if (_htcpExt != null)
                {
                    _htcpExt.Stop();
                    _htcpExt = null;
                }
                Protocol           = HProtocol.Modern;
                _toClientS         = _toServerS = _socketCount = 0;
                _clientB           = _serverB = _clientC = _serverC = null;
                _hasOfficialSocket = RequestEncrypted = ResponseEncrypted = false;
                ClientEncrypt      = ClientDecrypt = ServerEncrypt = ServerDecrypt = null;
                if (Disconnected != null)
                {
                    var disconnectedEventArgs = new DisconnectedEventArgs();
                    Disconnected(this, disconnectedEventArgs);
                    if (disconnectedEventArgs.UnsubscribeFromEvents)
                    {
                        SKore.Unsubscribe(ref Connected);
                        SKore.Unsubscribe(ref DataToClient);
                        SKore.Unsubscribe(ref DataToServer);
                        SKore.Unsubscribe(ref Disconnected);
                        base.Dispose(false);
                    }
                }
            }
        }
Пример #11
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();
        }
Пример #12
0
        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");
        }
Пример #13
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();
                }
            }
        }
Пример #14
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();
            }
        }
Пример #15
0
        public void Disconnect()
        {
            if (!_disconnectAllowed)
            {
                return;
            }
            _disconnectAllowed = false;

            lock (_disconnectLock)
            {
                if (_clientS != null)
                {
                    _clientS.Shutdown(SocketShutdown.Both);
                    _clientS.Close();
                    _clientS = null;
                }
                if (_serverS != null)
                {
                    _serverS.Shutdown(SocketShutdown.Both);
                    _serverS.Close();
                    _serverS = null;
                }

                ResetHost();
                if (_htcpExt != null)
                {
                    _htcpExt.Stop();
                    _htcpExt = null;
                }
                _toClientS         = _toServerS = _socketCount = 0;
                _clientB           = _serverB = _clientC = _serverC = null;
                OutgoingEncrypt    = OutgoingDecrypt = IncomingEncrypt = IncomingDecrypt = null;
                _hasOfficialSocket = _grabHeaders = IsOutgoingEncrypted = IsIncomingEncrypted = false;

                OnDisconnected(EventArgs.Empty);
            }
        }
Пример #16
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();
        }
Пример #17
0
 public NetServer(int port)
 {
     _listener = new TcpListenerEx(IPAddress.Any, port);
     SetupObservable();
 }
 public AsyncServerDemo(int port)
 {
     cancel   = new CancellationTokenSource();
     listener = new TcpListenerEx(IPAddress.Any, port);
 }
Пример #19
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();
        }
Пример #20
0
 public ITcpServerWorker Init(Socket workerTcpSocket, TcpListenerEx tcpListener)
 {
     _workerSocket = workerTcpSocket;
     _server       = tcpListener;
     return(this);
 }
Пример #21
0
 public NetServer(IPEndPoint localEP)
 {
     _listener = new TcpListenerEx(localEP);
     _listener.ExclusiveAddressUse = true;
     SetupObservable();
 }
Пример #22
0
 public NetServer(IPAddress localaddr, int port)
 {
     _listener = new TcpListenerEx(localaddr, port);
     SetupObservable();
 }