Example #1
0
        ///<summary>Disposes of the resources (other than memory) used by the Listener.</summary>
        ///<remarks>Stops listening and disposes <em>all</em> the client objects. Once disposed, this object should not be used anymore.</remarks>
        ///<seealso cref ="System.IDisposable"/>
        public void Dispose()
        {
            if (IsDisposed)
            {
                return;
            }
            DateTime time = DateTime.Now;

            while (Clients.Count > 0)
            {
                ((Client)Clients[0]).Dispose();
                if (time < DateTime.Now - TimeSpan.FromMinutes(1))
                {
                    Clients.Clear();
                    break;
                }
            }
            try {
                ListenSocket.Shutdown(SocketShutdown.Both);
            } catch {}
            try
            {
                if (ListenSocket != null)
                {
                    ListenSocket.Close();
                }
            } catch { }
            m_IsDisposed = true;
        }
Example #2
0
 public override void OnAccept(IAsyncResult ar)
 {
     try
     {
         Socket inputSocket = ListenSocket.EndAccept(ar);
         if (inputSocket != null)
         {
             inputSocket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.KeepAlive, true);
             Socket outputSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
             outputSocket.Connect(MapTo);
             outputSocket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.KeepAlive, true);
             //inputSocket.ReceiveTimeout = 180000;
             //inputSocket.SendTimeout = 180000;
             //outputSocket.ReceiveTimeout = 180000;
             //outputSocket.SendTimeout = 180000;
             forwarderTx = GetInputToOutputForwarder(inputSocket, outputSocket);
             forwarderRx = GetOutputToInputForwarder(outputSocket, inputSocket);
             AddClient(forwarderTx);
             AddClient(forwarderRx);
             forwarderTx.StartForward();
             forwarderRx.StartForward();
         }
     }
     catch { }
     try
     {
         //Restart Listening
         ListenSocket.BeginAccept(new AsyncCallback(this.OnAccept), ListenSocket);
     }
     catch
     {
         Dispose();
     }
 }
Example #3
0
 ///<summary>Called when there's an incoming client connection waiting to be accepted.</summary>
 ///<param name="ar">The result of the asynchronous operation.</param>
 public override async Task OnAccept(SocketConnection socket)
 {
     Console.WriteLine(socket.RemoteEndPoint + " => " + socket.LocalEndPoint);
     try
     {
         if (socket != null)
         {
             SocksClient socksClient = new SocksClient(socket, new DestroyDelegate(this.RemoveClient), AuthList);
             AddClient(socksClient);
             await socksClient.StartHandshake();
         }
     }
     catch (Exception ex)
     {
         Console.WriteLine("[WARN] " + ex.Message + "\r\n" + ex.StackTrace);
     }
     try
     {
         //Restart Listening
         var newSocket = await ListenSocket.AcceptAsync();
         await OnAccept(newSocket);
     }
     catch (Exception ex)
     {
         Console.WriteLine("[WARN] " + ex.Message + "\r\n" + ex.StackTrace);
         Dispose();
     }
 }
Example #4
0
        ///<summary>Called when there's an incoming client connection waiting to be accepted.</summary>
        ///<param name="ar">The result of the asynchronous operation.</param>
        public override void OnAccept(IAsyncResult ar)
        {
            try
            {
                Socket NewSocket = ListenSocket.EndAccept(ar);

                if (NewSocket != null)
                {
                    HttpClient NewClient = new HttpClient(NewSocket, new DestroyDelegate(this.RemoveClient));
                    NewClient.StartHandshake();
                }
            }
            catch
            {
            }
            try
            {
                //Restart Listening
                ListenSocket.BeginAccept(new AsyncCallback(this.OnAccept), ListenSocket);
            }
            catch
            {
                Dispose();
            }
        }
Example #5
0
 public override void OnAccept(IAsyncResult ar)
 {
     try
     {
         Socket clientSocket = ListenSocket.EndAccept(ar);
         if (clientSocket != null)
         {
             var client = new HttpClient(clientSocket, RemoveClient, UpdataUrlLog);
             AddClient(client);
             client.StartHandshake();
         }
     }
     catch (Exception ex)
     {
         this.ExceptionHandler?.Invoke(ex);
     }
     try
     {
         ListenSocket.BeginAccept(OnAccept, ListenSocket);
     }
     catch (Exception ex)
     {
         this.ExceptionHandler?.Invoke(ex);
         Dispose();
     }
 }
Example #6
0
 ///<summary>Called when there's an incoming client connection waiting to be accepted.</summary>
 ///<param name="ar">The result of the asynchronous operation.</param>
 public override void OnAccept(IAsyncResult ar)
 {
     try
     {
         Socket NewSocket = ListenSocket.EndAccept(ar);
         if (NewSocket != null)
         {
             PortMapClient NewClient = new PortMapClient(NewSocket, RemoveClient, MapTo);
             AddClient(NewClient);
             NewClient.StartHandshake();
         }
     }
     catch
     {
     }
     try
     {
         //Restart Listening
         ListenSocket.BeginAccept(new AsyncCallback(OnAccept), ListenSocket);
     }
     catch
     {
         Dispose();
     }
 }
Example #7
0
        public void StartUp()
        {
            if (IsRunning)
            {
                return;
            }

            IsRunning = false;

            try
            {
                ServerList.Init();

                UploadBandwidthThrottler.Start();

                DownloadQueue.Init();

                ListenSocket.StartListening();

                ClientUDP.Create();

                if (Preference.DoesAutoConnect)
                {
                    StartConnection();
                }

                IsRunning = true;
            }
            catch (Exception ex)
            {
                MpdUtilities.DebugLogError("MuleApplication StartUp Fail",
                                           ex);
            }
        }
Example #8
0
 ///<summary>Called when there's an incoming client connection waiting to be accepted.</summary>
 ///<param name="ar">The result of the asynchronous operation.</param>
 public override void OnAccept(IAsyncResult ar)
 {
     try {
         Socket NewSocket = ListenSocket.EndAccept(ar);
         //Console.WriteLine("Connection from " + NewSocket.RemoteEndPoint);
         if (NewSocket != null)
         {
             if (WhitelistIPs != null && WhitelistIPs.Count > 0 && !WhitelistIPs.Contains((NewSocket.RemoteEndPoint as IPEndPoint).Address.ToString()))
             {
                 //TODO: Log this
                 Console.WriteLine("Invalid connection from " + NewSocket.RemoteEndPoint);
                 try
                 {
                     NewSocket.Close();
                 }
                 catch { }
             }
             else
             {
                 SocksClient NewClient = new SocksClient(NewSocket, new DestroyDelegate(this.RemoveClient), AuthList);
                 AddClient(NewClient);
                 NewClient.StartHandshake();
             }
         }
     } catch {}
     try {
         //Restart Listening
         ListenSocket.BeginAccept(new AsyncCallback(this.OnAccept), ListenSocket);
     } catch {
         Dispose();
     }
 }
Example #9
0
        static void Main(string[] args)
        {
            JSON json = new JSON();

            byte[] b1 = json.Serialize("text");
            byte[] b2 = json.Serialize(new Exception("excetpion text"));
            byte[] b3 = json.Serialize(new int[3] {
                1, 2, 1
            });
            byte[] b4 = json.Serialize(new ListenSocket("127.0.0.1", 1234));

            object o1 = json.Deserialize(b1);
            object o2 = json.Deserialize(b2);
            object o3 = json.Deserialize(b3);
            object o4 = json.Deserialize(b4);

            try
            {
                QueueConveyor  queueConveyor  = new QueueConveyor();
                ListenSocket   listenSocket   = new ListenSocket("127.0.0.1", 8001);
                ConveyorServer conveyorServer = new ConveyorServer(queueConveyor, listenSocket);
                conveyorServer.StartLisetn();
            }
            catch (Exception err)
            {
                Console.WriteLine(err.Message);
            }
            Console.WriteLine("Нажмите любую клавишу для продолжения");
            Console.ReadKey();
        }
Example #10
0
        private void StartListening()
        {
            Sea = new SocketAsyncEventArgs();
            AcceptReset.Reset();

            Sea.Completed += (s, a) => {
                HandleSocket(Sea.AcceptSocket);
                AcceptReset.Set();
            };

            try
            {
                if (!ListenSocket.AcceptAsync(Sea))
                {
                    AcceptReset.Set();
                    HandleSocket(Sea.AcceptSocket);
                }
            }
            catch (Exception ex)
            {
                OnLog(ex.ToString());
            }

            AcceptReset.WaitOne();

            Sea.Dispose();
        }
Example #11
0
	///<summary>Restarts listening on the selected IP address and port.</summary>
	///<remarks>This method is automatically called when the listening port or the listening IP address are changed.</remarks>
	///<exception cref="SocketException">There was an error while creating the listening socket.</exception>
	protected void Restart() {
		//If we weren't listening, do nothing
		if (ListenSocket == null)
			return;
		ListenSocket.Close();
		Start();
	}
        ///<summary>Called when there's an incoming client connection waiting to be accepted.</summary>
        ///<param name="ar">The result of the asynchronous operation.</param>
        public override void OnAccept(IAsyncResult ar)
        {
            try
            {
                Socket NewSocket = ListenSocket.EndAccept(ar);
                try
                {
                    //Restart Listening
                    ListenSocket.BeginAccept(new AsyncCallback(OnAccept), ListenSocket);
                }
                catch
                {
                    Dispose();
                }
                if (NewSocket != null)
                {
                    HttpClient NewClient = new HttpClient(NewSocket, RemoveClient);
                    AddClient(NewClient);
                    NewClient.StartHandshake();

                    if (OnClientAdded != null)
                    {
                        OnClientAdded.Invoke(NewClient);
                    }
                }
            }
            catch
            {
            }
        }
Example #13
0
        public override void OnAccept(IAsyncResult ar)
        {
            try
            {
                Socket newSocket = ListenSocket.EndAccept(ar);
                if (newSocket != null)
                {
                    HttpClient NewClient = new HttpClient(newSocket, new DestroyDelegate(this.RemoveClient), Validator);
                    AddClient(NewClient);
                    NewClient.StartHandshake();
                }
            }
            catch (Exception ex)
            {
                Log.Write(MethodInfo.GetCurrentMethod(), ex);
            }

            try
            {
                ListenSocket.BeginAccept(new AsyncCallback(this.OnAccept), ListenSocket);
            }
            catch (Exception ex)
            {
                Log.Write(MethodInfo.GetCurrentMethod(), ex);
                Dispose();
            }
        }
Example #14
0
 public void Dispose()
 {
     if (!IsDisposed)
     {
         while (Clients.Count > 0)
         {
             ((Client)Clients[0]).Dispose();
         }
         try
         {
             if (ListenSocket.Connected)
             {
                 ListenSocket.Shutdown(SocketShutdown.Both);
             }
         }
         catch (SocketException se)
         {
             System.Diagnostics.Debug.WriteLine(se);
         }
         catch { }
         finally
         {
             if (ListenSocket != null)
             {
                 ListenSocket.Close();
             }
             IsDisposed = true;
         }
     }
 }
Example #15
0
 public void Dispose()
 {
     if (!IsDisposed)
     {
         while (Clients.Count > 0)
         {
             ((Client)Clients[0]).Dispose();
         }
         try
         {
             ListenSocket.Shutdown(SocketShutdown.Both);
         }
         catch
         {
         }
         finally
         {
             if (ListenSocket != null)
             {
                 ListenSocket.Close();
             }
             IsDisposed = true;
         }
     }
 }
Example #16
0
        public void Dispose()
        {
            if (IsDisposed)
            {
                return;
            }

            while (Clients.Count > 0)
            {
                Clients[0].Dispose();
            }

            try
            {
                ListenSocket.Shutdown(SocketShutdown.Both);
            }
            catch (Exception ex)
            {
                Log.Write(MethodInfo.GetCurrentMethod(), ex);
            }

            if (ListenSocket != null)
            {
                ListenSocket.Close();
            }

            _IsDisposed = true;
        }
        public void StartAccept()
        {
            SocketAsyncEventArgs acceptEventArg;

            //Get a SocketAsyncEventArgs object to accept the connection.
            //Get it from the pool if there is more than one in the pool.
            //We could use zero as bottom, but one is a little safer.
            if (this.PoolOfAcceptEventArgs.Count > 1)
            {
                try
                {
                    acceptEventArg = this.PoolOfAcceptEventArgs.Pop();
                }
                //or make a new one.
                catch
                {
                    acceptEventArg = CreateNewSaeaForAccept(PoolOfAcceptEventArgs);
                }
            }
            //or make a new one.
            else
            {
                acceptEventArg = CreateNewSaeaForAccept(PoolOfAcceptEventArgs);
            }


            bool willRaiseEvent = ListenSocket.AcceptAsync(acceptEventArg);

            if (!willRaiseEvent)
            {
                ProcessAccept(acceptEventArg);
            }
        }
Example #18
0
 public void Restart()
 {
     if (ListenSocket != null)
     {
         ListenSocket.Close();
         Start();
     }
 }
Example #19
0
        private static async void BeginSocket()
        {
            var orange = new ListenSocket(SocketType.Stream, ProtocolType.Tcp);

            orange.Bind(new IPEndPoint(IPAddress.Loopback, 8087));

            await orange.Listen(120);
        }
Example #20
0
 public void Stop()
 {
     if (ListenSocket == null)
     {
         return;
     }
     ListenSocket.Close();
 }
Example #21
0
        private void StartConnect(SocketAsyncEventArgs connectEventArgs)
        {
            bool willRaiseEvent = ListenSocket.ConnectAsync(connectEventArgs);

            if (!willRaiseEvent)
            {
                ProcessConnect(connectEventArgs);
            }
        }
Example #22
0
 ///<summary>Called when there's a connection from the local FTP client waiting to be accepted.</summary>
 ///<param name="ar">The result of the asynchronous operation.</param>
 private void OnPasvAccept(IAsyncResult ar)
 {
     try {
         ClientSocket = ListenSocket.EndAccept(ar);
         StartHandshake();
     } catch {
         Dispose();
     }
 }
Example #23
0
        public int ReceiveMessagesOnListenSocket(ListenSocket socket, ref NetworkingMessage[] messages, int maxMessages)
        {
            IntPtr nativeMessages = IntPtr.Zero;
            int    messagesCount  = Native.SteamAPI_ISteamNetworkingSockets_ReceiveMessagesOnListenSocket(nativeSockets, socket, out nativeMessages, maxMessages);

            MarshalMessages(nativeMessages, ref messages, messagesCount);

            return(messagesCount);
        }
Example #24
0
        public bool CloseListenSocket(ListenSocket socket, string remoteReason)
        {
            if (remoteReason.Length > Library.maxCloseMessageLength)
            {
                throw new ArgumentOutOfRangeException("remoteReason");
            }

            return(Native.SteamAPI_ISteamNetworkingSockets_CloseListenSocket(nativeSockets, socket, remoteReason));
        }
Example #25
0
 protected void Restart()
 {
     if (ListenSocket == null)
     {
         return;
     }
     ListenSocket.Close();
     Start();
 }
Example #26
0
 public void BeginAccept()
 {
     while (IsBeginAccept)
     {
         BeginAccpetControl.Reset();
         ListenSocket.BeginAccept(new AsyncCallback(BeginAcceptCallBack), ListenSocket);
         BeginAccpetControl.WaitOne(); //等待Clinet...
     }
     //===================
 }
Example #27
0
 /// <summary>
 /// Создание нового сервера, работающего с указанным сервером
 /// </summary>
 /// <param name="Conveyor"></param>
 public ConveyorServer(IConveyor Conveyor, ListenSocket ListenSocket)
 {
     ///Сохранение конвейера
     conveyor = Conveyor;
     //Созранение сокета
     listenSocket = ListenSocket;
     //Добавляется метод для прослушивания получаемых сообщений
     listenSocket.AcceptMessage += AcceptMessage;
     //СОздание объекта для сериализации
     json = new JSON();
 }
Example #28
0
 ///<summary>Called when there's a connection from the remote FTP server waiting to be accepted.</summary>
 ///<param name="ar">The result of the asynchronous operation.</param>
 private void OnPortAccept(IAsyncResult ar)
 {
     try {
         DestinationSocket = ListenSocket.EndAccept(ar);
         ListenSocket.Close();
         ListenSocket = null;
         StartHandshake();
     } catch {
         Dispose();
     }
 }
Example #29
0
        public override async Task AcceptAsync(TestContext ctx, CancellationToken cancellationToken)
        {
            ctx.LogDebug(5, $"{ME} ACCEPT: {ListenSocket.LocalEndPoint}");
            if (Socket != null)
            {
                throw new NotSupportedException();
            }
            Socket = await ListenSocket.AcceptAsync(cancellationToken).ConfigureAwait(false);

            remoteEndPoint = (IPEndPoint)Socket.RemoteEndPoint;
            ctx.LogDebug(5, $"{ME} ACCEPT #1: {ListenSocket.LocalEndPoint} {remoteEndPoint}");
        }
Example #30
0
	///<summary>Disposes of the resources (other than memory) used by the Listener.</summary>
	///<remarks>Stops listening and disposes <em>all</em> the client objects. Once disposed, this object should not be used anymore.</remarks>
	///<seealso cref ="System.IDisposable"/>
	public void Dispose() {
		if (IsDisposed)
			return;
		while (Clients.Count > 0) {
			((Client)Clients[0]).Dispose();
		}
		try {
			ListenSocket.Shutdown(SocketShutdown.Both);
		} catch {}
		if (ListenSocket != null)
			ListenSocket.Close();
		m_IsDisposed = true;
	}