AllowNatTraversal() public method

public AllowNatTraversal ( bool allowed ) : void
allowed bool
return void
示例#1
0
 /// <summary>
 /// Initializes a new instance of the <see cref="libanimus.Networking.TelnetUpstream"/> class.
 /// </summary>
 public TelnetUpstream()
 {
     Clients = new List<TcpClient> ();
     Actions = new List<HostAction> ();
     globalLog = new List<string> ();
     notifications = new Dictionary<TcpClient, List<string>> ();
     var local = IPAddress.Any;
     listener = new TcpListener (local, 23);
     listener.AllowNatTraversal (true);
     try {
         listener.Start ();
     } catch {
         NetworkManager.Instance.Broadcast ("Failed to start telnet client.");
         return;
     }
     Task.Factory.StartNew (Listen).ContinueWith (task => {
         if (task.IsFaulted) {
             // Log exception here
             Console.WriteLine ("Telnet listener task faulted.");
         }
         try {
             listener.Stop ();
         }
         finally {
             listener = null;
         }
     });
 }
 public void initializeListener()
 {
     listener = new TcpListener(new IPEndPoint(IPAddress.Any, Multiplayer.PORT));
     listener.AllowNatTraversal(true);
     listener.Start();
     listener.BeginAcceptTcpClient(AcceptTcpConnectionCallback, listener);
 }
示例#3
0
        /// <summary>
        /// 异步TCP服务器
        /// </summary>
        /// <param name="localIPAddress">监听的IP地址</param>
        /// <param name="listenPort">监听的端口</param>
        public AsyncTcpServer(IPAddress localIPAddress, int listenPort)
        {
            Address = localIPAddress;
            Port = listenPort;
            this.Encoding = Encoding.Default;

            _clients = new List<Object>();

            _listener = new TcpListener(Address, Port);
            _listener.AllowNatTraversal(true);
        }
示例#4
0
    /// <summary>
    /// 异步TCP服务器
    /// </summary>
    /// <param name="localIPAddress">监听的IP地址</param>
    /// <param name="listenPort">监听的端口</param>
    public AsyncTcpServer(IPAddress localIPAddress, int listenPort)
    {
      Address = localIPAddress;
      Port = listenPort;
      this.Encoding = Encoding.Default;

      _clients = new ConcurrentDictionary<string, TcpClientState>();

      _listener = new TcpListener(Address, Port);
      _listener.AllowNatTraversal(true);
    }
 public void InitializeConfiguration(int LocalPort)
 {
     _listenPort = LocalPort;
     _ipEndPoint = new IPEndPoint(IPAddress.Parse("127.0.0.1"), _listenPort);
     // TODO: Implement this method
     //throw new NotImplementedException();
     if (isrunning == true)
     {
         StopService();
     }
     _listenClient = new TcpListener(_ipEndPoint);
     _listenClient.AllowNatTraversal(true);
 }
示例#6
0
        public void Start()
        {
            try
            {
                server = TcpListener.Create(localAddress.Port.Value);
                server.ExclusiveAddressUse = false;
                server.AllowNatTraversal(true);
                server.Start(100);

                WaitForClient();
            }
            catch (Exception x)
            {
                Console.WriteLine(x);
            }
        }
 /// <summary>
 /// Initiates the TCP listener with the specified IPEndpoint.
 /// <para>(Called by BeginSetup.)</para>
 /// </summary>
 /// <param name="endPoint">The IP and Port information to listen on.</param>
 private void EndSetup( IPEndPoint endPoint )
 {
     Listener = new TcpListener( endPoint );
     Listener.AllowNatTraversal( true );
 }
示例#8
0
文件: Program.cs 项目: PsichiX/Aegis
 private void SpawnEyeListenerTask()
 {
     Task.Run(() =>
     {
         lock (m_lock)
         {
             try
             {
                 m_eyeListener = new TcpListener(IPAddress.Any, m_settingsModel.EyePort);
                 m_eyeListener.AllowNatTraversal(true);
                 m_eyeListener.Start();
             }
             catch
             {
                 m_eyeListener = null;
                 return;
             }
         }
         Program.SaveWriteLine("* Listening for eye clients on port: " + m_settingsModel.EyePort);
         while (m_running)
         {
             try
             {
                 var client = m_eyeListener.AcceptTcpClient(new TimeSpan(1000));
                 var tokenBytes = new byte[TOKEN_SIZE];
                 var stream = client.GetStream();
                 var tokenSize = stream.Read(tokenBytes, 0, TOKEN_SIZE);
                 if (tokenSize == TOKEN_SIZE)
                 {
                     var ascii = new ASCIIEncoding();
                     var token = ascii.GetString(tokenBytes);
                     if (token == m_settingsModel.Token)
                     {
                         token = Guid.NewGuid().ToString();
                         if (token.Length < TOKEN_SIZE)
                             for (int i = token.Length; i < TOKEN_SIZE; ++i)
                                 token += " ";
                         else if (token.Length > TOKEN_SIZE)
                             token = token.Substring(0, TOKEN_SIZE);
                         lock (m_eyeClientsLock)
                         {
                             if (m_eyeClients.ContainsKey(token))
                                 stream.WriteByte(0);
                             else
                             {
                                 m_eyeClients[token] = client;
                                 tokenBytes = ascii.GetBytes(token);
                                 stream.Write(tokenBytes, 0, tokenBytes.Length);
                                 Program.SaveWriteLine("* Eye connected: " + token);
                                 client.ReceiveTimeout = 1000;
                                 SpawnEyeReceiverTask(token);
                             }
                         }
                     }
                 }
             }
             catch { }
             Thread.Sleep(100);
         }
         lock (m_lock)
         {
             if (m_eyeListener != null)
                 m_eyeListener.Stop();
             m_eyeListener = null;
         }
         Program.SaveWriteLine("* Stop listening for eye clients");
     });
 }
示例#9
0
        public string StartServer()
        {
            bool ssl = MainForm.Conf.SSLEnabled;
            if (ssl && !string.IsNullOrEmpty(MainForm.Conf.SSLCertificate))
                X509.LoadCertificate(MainForm.Conf.SSLCertificate);

            string message = "";
            try
            {
                _myListener = new TcpListener(ListenerAddress, MainForm.Conf.LANPort) { ExclusiveAddressUse = false };
                if (MainForm.Conf.IPMode=="IPv6")
                {
                     _myListener.AllowNatTraversal(true);
                }
                _myListener.Start(200);

                WebSocketServer?.Close();

                WebSocketServer = new WebSocketServer(this);
                ServerStartupFailed = false;
            }
            catch (Exception e)
            {
                Logger.LogExceptionToFile(e,"Server");
                StopServer();
                message = "Could not start local iSpy server - please select a different LAN port in settings. The port specified is in use. See the log file for more information.";
                ServerStartupFailed = true;
            }
            if (message != "")
            {
                Logger.LogMessageToFile(message, "Server");
                return message;
            }
            try 
            {
                //start the thread which calls the method 'StartListen'
                if (Running)
                {
                    while (_th.ThreadState == ThreadState.AbortRequested)
                    {
                        Application.DoEvents();
                    }
                }
                
            }
            catch (Exception e)
            {
                message = e.Message;
                Logger.LogExceptionToFile(e, "Server");
            }

            lock (_threadLock)
            {
                _th = new Thread(StartListen) {IsBackground = true};
                _th.Start();
            }
            return message;
        }
示例#10
0
        public string StartServer()
        {
            if (!String.IsNullOrEmpty(MainForm.Conf.SSLCertificate))
                X509.LoadCertificate(MainForm.Conf.SSLCertificate);

            string message = "";
            try
            {
                if (MainForm.Conf.IPMode=="IPv6")
                {
                    _myListener = new TcpListener(IPAddress.IPv6Any, MainForm.Conf.LANPort) { ExclusiveAddressUse = false };
                     _myListener.AllowNatTraversal(true);
                }
                else
                {
                    _myListener = new TcpListener(IPAddress.Any, MainForm.Conf.LANPort)
                                        {ExclusiveAddressUse = false};
                }
                _myListener.Start(200);
            }
            catch (Exception e)
            {
                MainForm.LogExceptionToFile(e);
                StopServer();
                message = "Could not start local iSpy server - please select a different LAN port in settings. The port specified is in use. See the log file for more information.";
            }
            if (message != "")
            {
                MainForm.LogMessageToFile(message);
                return message;
            }
            try
            {
                //start the thread which calls the method 'StartListen'
                if (Running)
                {
                    while (_th.ThreadState == ThreadState.AbortRequested)
                    {
                        Application.DoEvents();
                    }
                }

            }
            catch (Exception e)
            {
                message = e.Message;
                MainForm.LogExceptionToFile(e);
            }

            lock (_threadLock)
            {
                _th = new Thread(StartListen);
                _th.Start();
            }
            return message;
        }
示例#11
0
        public void Start()
        {
            // Check if a worker isn't already running
            if (isWorkerAlive())
            {
                Log.d("Could not start server, an instance is already running.");
                return;
            }

            m_Continue = true;
            m_Worker = new Thread(() =>
            {
                TcpListener listener = new TcpListener(IPAddress.Any, m_Port);
                listener.AllowNatTraversal(true);
                listener.ExclusiveAddressUse = false;
                listener.Server.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true);

                listener.Start();

                while (m_Continue)
                {
                    Log.d("Waiting for connection...");
                    TcpClient client = listener.AcceptTcpClient();

                    Log.d("Connection accepted.");
                    NetworkStream ns = client.GetStream();
            #if !DEBUG
                    ns.ReadTimeout = SOCKET_READ_TIMEOUT;
            #endif

                    try
                    {
                        // Sends the HELLO message
                        Byte[] sendBytes = Encoding.UTF8.GetBytes(GetHello());
                        ns.Write(sendBytes, 0, sendBytes.Length);
                        ns.Flush();
                        Log.d("HELLO sent.");

                        // Reads NetworkStream into a byte buffer.
                        byte[] bytes = new byte[client.ReceiveBufferSize];

                        // Read can return anything from 0 to numBytesToRead.
                        // This method blocks until at least one byte is read.
                        StringBuilder readString = null;
                        do
                        {
                            Log.d("Waiting for data...");

                            readString = new StringBuilder();
                            int numberOfBytesRead = 0;

                            // Incoming message may be larger than the buffer size.
                            do
                            {
                                numberOfBytesRead = ns.Read(bytes, 0, bytes.Length);
                                readString.AppendFormat("{0}", Encoding.UTF8.GetString(bytes, 0, numberOfBytesRead).TrimEnd('\0', '\r', '\n'));
                            }
                            while(ns.DataAvailable);

                            Log.d("Received : " + readString.ToString() + " - " + numberOfBytesRead.ToString() + " bytes");

                        }
                        while (OnData(readString.ToString(), ns));
                    }
                    catch (Exception e)
                    {
                        Log.d(e.ToString());
                    }
                    finally
                    {
                        ns.Close();
                        client.Close();
                        Log.d("Connection closed.");
                    }
                }

                listener.Stop();
            });

            m_Worker.Start();
        }
示例#12
0
 // Listen Loop
 protected void ListenThread(object param)
 {
     // Start Listening
     try
     {
         object[] parameters = (object[])param;
         IPAddress ip = (IPAddress)parameters[0];
         ushort port = (ushort)parameters[1];
         IPEndPoint ipep = new IPEndPoint(ip, port);
         lock (ListenerStartStopLock)
         {
             if (tcpl == null)
             {
                 tcpl = new TcpListener(ipep);
                 tcpl.AllowNatTraversal(true);
             }
             bListening = true;
             tcpl.Start(10);
         }
     }
     catch (Exception ex)
     {
         bListening = false;
         ex.ToString();
         try
         {
             if (tcpl != null)
                 tcpl.Stop();
         }
         catch (Exception) { }
         RaiseListenStop();
         return;
     }
     // Start accepting clients
     TcpClient client = null;
     string key = "";
     try
     {
         while (bListening)
         {
             client = null;
             key = "";
             client = tcpl.AcceptTcpClient();
             key = client.Client.RemoteEndPoint.ToString();
             Thread clientReadThread;
             Thread clientSendThread;
             lock (clientList)
             {
                 if (clientList.ContainsKey(key))
                 {
                     clientList[key].Disconnect();
                     clientList.Remove(key);
                     RaiseClientDisconnect(key);
                 }
                 clientReadThread = new Thread(ClientReceiveThread);
                 clientSendThread = new Thread(ClientSendThread);
                 clientList.Add(key, new ClientThreadPack(clientReadThread, clientSendThread, client, key));
             }
             clientReadThread.Start(key);
             clientSendThread.Start(key);
             RaiseClientConnect(key);
         }
     }
     catch (SocketException ex)
     {
         if (ex.ErrorCode == 10004)
         {
             // TcpListener Stop function was called while waiting for a client to connect
         }
         ex.ToString();
     }
     catch (Exception ex)
     {
         ex.ToString();
     }
     // We are done listening.
     bListening = false;
     try
     {
         if (tcpl != null)
             tcpl.Stop();
     }
     catch (Exception) { }
     // I believe this disconnects a client that may be not completely finished connecting.
     if (client != null)
         try
         {
             client.Close();
         }
         catch (Exception) { }
     DisconnectAllClients();
     RaiseListenStop();
 }
示例#13
0
        /// <summary>
        ///     Start this listener.
        /// </summary>
        /// <remarks>
        ///     This also pre-configures 20 channels that can be used and reused during the lifetime of
        ///     this listener.
        /// </remarks>
        /// <param name="address">Address to accept connections on</param>
        /// <param name="port">Port to use. Set to <c>0</c> to let the OS decide which port to use. </param>
        /// <seealso cref="LocalPort" />
        public virtual void Start(IPAddress address, int port)
        {
            if (port < 0)
                throw new ArgumentOutOfRangeException("port", port, "Port must be 0 or more.");
            if (_listener != null)
                throw new InvalidOperationException("Already listening.");

            _shuttingDown = false;
            _listener = new TcpListener(address, port);
            _listener.AllowNatTraversal(true);
            _listener.Start();

            for (var i = 0; i < 20; i++)
            {
                var decoder = _configuration.DecoderFactory();
                var encoder = _configuration.EncoderFactory();
                var channel = _channelFactory.Create(_bufferPool.Pop(), encoder, decoder);
                _channels.Push(channel);
            }

            _listener.BeginAcceptSocket(OnAcceptSocket, null);
        }
示例#14
0
 public static void StartServer()
 {
     Console.WriteLine ("Starting server...");
     _server = new TcpListener (new IPEndPoint (IPAddress.Any, 25565));
     _server.AllowNatTraversal (true);
     Console.WriteLine ("Server started, accepting connections");
     _server.Start (1);
     _server.BeginAcceptSocket (new AsyncCallback (AcceptCall), null);
 }