EndAcceptTcpClient() 공개 메소드

public EndAcceptTcpClient ( IAsyncResult asyncResult ) : TcpClient
asyncResult IAsyncResult
리턴 TcpClient
예제 #1
0
파일: Program.cs 프로젝트: Maartyl/cs-chan
        public static void Main(string[] args)
        {
            Action<object> cw = Console.WriteLine;
              cw("* any");
              cw(IPAddress.Any);
              cw(IPAddress.IPv6Any);
              cw("* loopback");
              cw(IPAddress.Loopback);
              cw(IPAddress.IPv6Loopback);
              cw("* none");
              cw(IPAddress.None);
              cw(IPAddress.IPv6None);
              cw("* bc4"); //trivia: there is no bc6, only multicast
              cw(IPAddress.Broadcast);

              TcpListener l = new TcpListener(IPAddress.Any, 7896);
              l.Start();
              l.BeginAcceptTcpClient(ar => {
            var c = l.EndAcceptTcpClient(ar);
            l.Stop();
            //var s = new StreamWriter(c.GetStream());
            //s.WriteLine("test writer : needed");
            //s.Flush();
            var bs = System.Text.Encoding.UTF8.GetBytes("test direct : not needed");
            c.GetStream().Write(bs, 0, bs.Length);
            c.Close();
              }, l);

              //start client
              var q = new TcpClient("localhost", 7896);
              var qs = new StreamReader(q.GetStream());
              Console.WriteLine(qs.ReadLine());
              // l.Stop();
        }
예제 #2
0
        private void OnConnect(IAsyncResult ar)
        {
            SOCK.TcpClient newClient = null;
            try
            {
                newClient = m_tcpListener.EndAcceptTcpClient(ar);
            }
            catch (Exception)
            {
            }

            if (null != newClient)
            {
                System.Net.IPEndPoint newEp = (System.Net.IPEndPoint)newClient.Client.RemoteEndPoint;

                m_Settings.WriteMessageToLog(
                    LogMessageType.Information + 1,
                    string.Format(CultureInfo.CurrentUICulture, "Client {0}:{1} connected.", newEp.Address, newEp.Port)
                    );

                SipProxyServer sps = new SipProxyServer(newClient, m_Settings);
                sps.PipeDead += Proxy_PipeDead;
                m_ClientConnections.Add(newEp, sps);
            }

            m_tcpListener.BeginAcceptTcpClient(OnConnect, null);
        }
예제 #3
0
        private void ThreadProc()
        {
            TcpListener listner = null;
            try
            {
                listner = new TcpListener(IPAddress.Any, _connectionString.Port);
                listner.Start(1);
                Thread clientThread = null;
                do
                {
                    try
                    {
                        //_tcpClientConnected.Reset();
                        IAsyncResult aResult = listner.BeginAcceptTcpClient(null, null);

                        int eventIndex = WaitHandle.WaitAny(new[] { _exit, aResult.AsyncWaitHandle });
                        if (eventIndex == 0) break;

                        //using (TcpClient client = listner.EndAcceptTcpClient(aResult))
                        //{
                        //    aResult.AsyncWaitHandle.Close();
                        //    ReadInLoop(client);
                        //}
                        TcpClient client = listner.EndAcceptTcpClient(aResult);
                        aResult.AsyncWaitHandle.Close();
                        if (_tcpClientConnected != null)
                            _tcpClientConnected.Set();
                        else
                            _tcpClientConnected = new AutoResetEvent(false);
                        if (clientThread != null && clientThread.ThreadState == ThreadState.Running)
                            clientThread.Join();
                        clientThread = new Thread(ReadInLoop) { IsBackground = true };
                        clientThread.Start(client);

                        //_client = listner.EndAcceptTcpClient(aResult);
                        //aResult.AsyncWaitHandle.Close();
                        //listner.Stop();

                        //_client.Client.ReceiveTimeout = ReceiveTimeout;
                        //ReadInLoop();
                    }
                    catch (Exception ex)
                    {
                        _log.WriteError(string.Format("TcpExternalSystemServer: {0}", ex));
                        Thread.Sleep(5000);
                    }
                } while (!_exit.WaitOne(0));
                listner.Stop();
            }
            catch (Exception ex)
            {
                _log.WriteError(string.Format("TcpExternalSystemServer.ThreadProc:\n{0}",ex));
            }
            finally
            {
                listner = null;
            }
        }
        private void ConnectionAccepted(IAsyncResult ar)
        {
            if (!StopThread)
            {
                // Dim listener As TcpListener = CType(ar.AsyncState, TcpListener)
                TcpClient client = server.EndAcceptTcpClient(ar);

                byte[] bytes = new byte[1025];

                // Get a stream object for reading and writing
                NetworkStream stream = client.GetStream();

                int i = stream.Read(bytes, 0, bytes.Length);


                string header = "<html xmlns : msxsl = \"urn:schemas-Microsoft - com: xslt\"  meta content=\"en-us\" http-equiv=\"Content-Language\" /> " + "<meta content=\"text/html; charset=utf-16\" http-equiv=\"Content-Type\" /> " + "<meta http-equiv=\"refresh\" content=\"" + m_RefreshTime.ToString() + "\"> ";

                header += "<img src=\"data:image/png;base64,";
                byte[] b = System.Text.ASCIIEncoding.Default.GetBytes(header);
                stream.Write(b, 0, b.Length);

                byte[] Imgbytes = null;
                bmpScreenCapture = new Bitmap(m_SourceForm.Width, m_SourceForm.Height);
                m_SourceForm.Invoke(dcc);
                using (System.IO.MemoryStream ms = new System.IO.MemoryStream())
                {
                    bmpScreenCapture.Save(ms, System.Drawing.Imaging.ImageFormat.Png);
                    Imgbytes = ms.ToArray();
                }

                string s = Convert.ToBase64String(Imgbytes);
                Imgbytes = System.Text.ASCIIEncoding.Default.GetBytes(s);
                try
                {
                    stream.Write(Imgbytes, 0, Imgbytes.Length);

                    string trailer = " \"/>";
                    b = System.Text.ASCIIEncoding.Default.GetBytes(trailer);
                    stream.Write(b, 0, b.Length);


                    // Shutdown and end connection
                    client.Close();
                }
                catch (Exception ex)
                {
                }
            }

            if (!StopThread)
            {
                server.BeginAcceptTcpClient(ConnectionAccepted, server);
            }
        }
예제 #5
0
        /// <summary>
        ///	Server's main loop implementation.
        /// </summary>
        /// <param name="log"> The Logger instance to be used.</param>
        public void Run(Logger log)
        {
            try
            {
                _srv = new TcpListener(IPAddress.Loopback, _portNumber);
                _srv.Start();

                log.Start();

                AsyncCallback callback = null;

                callback = delegate(IAsyncResult iar)
                {
                    TcpClient socket = _srv.EndAcceptTcpClient(iar);
                    log.LogMessage("Listener - Waiting for connection requests.");
                    _srv.BeginAcceptTcpClient(callback, _srv);

                    // Process the previous request
                    try
                    {
                        socket.LingerState = new LingerOption(true, LingerTime);
                        log.LogMessage(String.Format("Listener - Connection established with {0}.",
                            socket.Client.RemoteEndPoint));

                        log.LogMessage(String.Format("Listener - Connection is going to last {0} seconds",
                            LingerTime));

                        // Instantiating protocol handler and associate it to the current TCP connection
                        Handler protocolHandler = new Handler(socket.GetStream(), log);

                        // Synchronously process requests made through de current TCP connection
                        protocolHandler.Run();
                    }
                    catch (Exception e)
                    {
                        MessageBox.Show(e.Message);
                    }

                    ShowInfo(Store.Instance);
                };

                log.LogMessage("Listener - Waiting for connection requests.");
                _srv.BeginAcceptTcpClient(callback, _srv);
            }
            catch (Exception)
            {
                log.LogMessage("Listener - Ending.");
                log.Stop();
                _srv.Stop();
            }
        }
예제 #6
0
        internal ClientConnection(ServerView father, TcpClient textTcp, String password, ArrayList name)
        {
            this._father = father;
            this._textTcp = textTcp;
            ChallengeMessage auth = new ChallengeMessage();
            auth.salt = new Random().Next().ToString();
            auth.sendMe(textTcp.GetStream()); //mando il sale
            ResponseChallengeMessage respo = ResponseChallengeMessage.recvMe(textTcp.GetStream());

            if (name.Contains(respo.username))
            {
                //connessione fallita
                ConfigurationMessage fail = new ConfigurationMessage("Nome utente già utilizzato");
                fail.sendMe(textTcp.GetStream());
                throw new ClientConnectionFail("Un client ha fornito un nome utente già utilizzato");
            }
            this._username = respo.username;
            if (Pds2Util.createPswMD5(password, auth.salt).Equals(respo.pswMd5))
            {
                //creo le connessioni per i socket clipboard e video
                IPAddress localadd = ((IPEndPoint)textTcp.Client.LocalEndPoint).Address;
                TcpListener lvideo = new TcpListener(localadd, 0);
                lvideo.Start();
                IAsyncResult videores = lvideo.BeginAcceptTcpClient(null, null);
                TcpListener lclip = new TcpListener(localadd, 0);
                lclip.Start();
                IAsyncResult clipres = lclip.BeginAcceptTcpClient(null, null);
                int porta_video = ((IPEndPoint)lvideo.LocalEndpoint).Port;
                int clip_video = ((IPEndPoint)lclip.LocalEndpoint).Port;
                new ConfigurationMessage(porta_video, clip_video, "Benvenuto")
                    .sendMe(textTcp.GetStream());
                _clipTcp = lclip.EndAcceptTcpClient(clipres);
                _videoTcp = lvideo.EndAcceptTcpClient(videores);
                //now the client is connected
                _textReceiver = new Thread(_receiveText);
                _textReceiver.IsBackground = true;
                _textReceiver.Start();
                _clipReceiver = new Thread(_receiveClipboard);
                _clipReceiver.IsBackground = true;
                _clipReceiver.Start();
            }
            else
            {
                //connessione fallita
                ConfigurationMessage fail = new ConfigurationMessage("password sbagliata");
                fail.sendMe(textTcp.GetStream());
                throw new ClientConnectionFail("Un client ha fornito una password sbagliata");
            }
        }
예제 #7
0
        private void AcceptTcpClientTaskComplete(IAsyncResult ar)
        {
            try {
                if (ar.AsyncState is TcpListener tcp_listener)
                {
                    var tcp_client = tcp_listener_.EndAcceptTcpClient(ar);

                    /* 新しいクライアントの受け入れ */
                    if (tcp_client != null)
                    {
                        /* Buffer Size */
                        tcp_client.SendBufferSize    = (int)devp_.SendBufferSize.Value;
                        tcp_client.ReceiveBufferSize = (int)devp_.RecvBufferSize.Value;

                        /* Reuse Address */
                        if (devp_.ReuseAddress.Value)
                        {
                            tcp_client.Client.SetSocketOption(
                                (devp_.AddressFamily.Value == AddressFamilyType.IPv6) ? (SocketOptionLevel.IPv6) : (SocketOptionLevel.IP),
                                SocketOptionName.ReuseAddress,
                                true);
                        }

                        /* Keep Alive設定 */
                        if (devp_.KeepAliveOnOff.Value)
                        {
                            SocketIOControl(
                                tcp_client.Client,
                                IOControlCode.KeepAliveValues,
                                (uint)((devp_.KeepAliveOnOff.Value) ? (1u) : (0u)),
                                (uint)devp_.KeepAliveTime_Value.Value,
                                (uint)devp_.KeepAliveInterval_Value.Value);
                        }

                        /* TTL設定 */
                        if (devp_.TTL_Unicast.Value)
                        {
                            tcp_client.Client.Ttl = (byte)devp_.TTL_Unicast_Value.Value;
                        }

                        /* クライアントリストへ追加 */
                        lock (tcp_clients_sync_) {
                            tcp_clients_.Add(new TcpClientObject(this, tcp_client));
                        }
                    }
                }
            } catch {
            }
        }
예제 #8
0
        private void AcceptCallback(IAsyncResult iar)
        {
            try
            {
                System.Net.Sockets.TcpListener listener = (System.Net.Sockets.TcpListener)iar.AsyncState;
                _connector  = listener.EndAcceptTcpClient(iar);
                _dataStream = _connector.GetStream();

                StateObject receveieData = new StateObject();
                receveieData.client = _connector;

                _dataStream.BeginRead(receveieData.buffer, 0, receveieData.buffer.Length, AcceptData, receveieData);
                _listener.BeginAcceptTcpClient(AcceptCallback, _listener);
            }
            catch (Exception ex)
            {
                SFLib.Logger.Exception(ex.Message);
            }
        }
예제 #9
0
    private void Accept(IAsyncResult ar)
    {
        try {
            System.Net.Sockets.TcpListener server = (TcpListener)ar.AsyncState;
            TcpClient client = server.EndAcceptTcpClient(ar);
            Receive(client.Client);

            /*
             * BackgroundWorker backWorker = new BackgroundWorker();
             * backWorker.WorkerReportsProgress = true;
             * backWorker.WorkerSupportsCancellation = true;
             *
             * backWorker.DoWork += this.backWorker_DoWork;
             * backWorker.ProgressChanged += this.backWorker_ProgressChanged;
             * backWorker.RunWorkerCompleted += this.backWorker_RunWorkerCompleted;
             *
             * backWorker.RunWorkerAsync(client);
             * _socketBackworkers.Add(backWorker);*/
        } catch (Exception ex) {
            Console.WriteLine(ex.ToString());
            error_text = ex.ToString();
        }
    }
예제 #10
0
        /// <summary>
        /// Comprueba si hay nuevos clientes para conectar
        /// </summary>
        private void ComprobarClienteConectado(IAsyncResult ar)
        {
            if (clientes == null)
            {
                clientes = new List <ClienteTCP>();
            }

            if (AceptarNuevasConexiones)
            {
                try
                {
                    ClienteTCP nuevoCliente = new ClienteTCP(listener.EndAcceptTcpClient(ar), "Servidor");
                    clientes.Add(nuevoCliente);

                    nuevoCliente.DatosRecibidos += new DelegadoComandoRecibido(DatosClienteRecibidos);
                    //Esperar más clientes
                    listener.BeginAcceptTcpClient(new AsyncCallback(ComprobarClienteConectado), null);

                    //Invocar el evento
                    InvocarEvento(ClienteConectado, ControlInvoke, nuevoCliente, null);
                }
                catch { }
            }
        }
예제 #11
0
파일: Program.cs 프로젝트: Baptista/PC
        /// <summary>
        ///	Server's main loop implementation.
        /// </summary>
        /// <param name="log"> The Logger instance to be used.</param>
        public Task<Boolean> Run(Logger log)
        {
            TcpListener srv = null;
            
            try
            {

                srv = new TcpListener(IPAddress.Loopback, portNumber);
                srv.Start();
                /////////////////////////////////////////////////////////////////
                /////////////////////////////APM/////////////////////////////////
                /////////////////////////////////////////////////////////////////
                AsyncCallback onAccepted = null;
                onAccepted = delegate(IAsyncResult ar)
                    {
                        TcpClient socket = null;

                        try
                        {
                            int timeout = (int)ar.AsyncState;
                            if (timeout == 0)
                                return;

                            int time = Environment.TickCount;

                            using (socket = srv.EndAcceptTcpClient(ar))
                            {
                                if(Environment.TickCount - time > timeout)
                                    return;
                                socket.LingerState = new LingerOption(true, 10);
                                log.LogMessage(String.Format("Listener - Connection established with {0}.",
                                                             socket.Client.RemoteEndPoint));
                                log.IncrementRequests();
                                // Instantiating protocol handler and associate it to the current TCP connection
                                Handler protocolHandler = new Handler(socket.GetStream(), log);
                                // Synchronously process requests made through de current TCP connection
                                protocolHandler.Run();

                                srv.BeginAcceptTcpClient(onAccepted, null);
                            }
                            Program.ShowInfo(Store.Instance);
                        }
                        catch (SocketException) { Console.WriteLine("Socket error"); }
                        catch (ObjectDisposedException) { }
                    };
                srv.BeginAcceptTcpClient(onAccepted, 20);
                Console.ReadLine();
                return null;
                //////////////////////////////////////////////////////
                //////////////////////////////////////////////////////
                //while (true)
                //{
                //    log.LogMessage("Listener - Waiting for connection requests.");
                //    using (TcpClient socket = srv.AcceptTcpClient())
                //    {
                //        socket.LingerState = new LingerOption(true, 10);
                //        log.LogMessage(String.Format("Listener - Connection established with {0}.",
                //            socket.Client.RemoteEndPoint));
                //        // Instantiating protocol handler and associate it to the current TCP connection
                //        Handler protocolHandler = new Handler(socket.GetStream(), log);
                //        // Synchronously process requests made through de current TCP connection
                //        protocolHandler.Run();
                //    }

                //    Program.ShowInfo(Store.Instance);
                //}

            }
            finally
            {
                log.LogMessage("Listener - Ending.");
                srv.Stop();
            }
        }
예제 #12
0
        private void StartListening(TcpListener server)
        {
            if (_shouldStop)
            {
                return;
            }
            server.BeginAcceptTcpClient(new AsyncCallback(delegate(IAsyncResult result)
                                                              {
                                                                  TcpClient client = null;
                                                                  try
                                                                  {
                                                                      client = server.EndAcceptTcpClient(result);
                                                                  }
                                                                  catch (Exception e)
                                                                  {
                                                                      LogManger.Error(e, this.GetType());
                                                                  }
                                                                  if (client != null)
                                                                  {
                                                                      ThreadPool.QueueUserWorkItem(ClientReceiveMessage, client);
                                                                  }

                                                                  StartListening(server);
                                                              }), server);
        }
예제 #13
0
		public void TestAsyncBasic()
		{
			var listener = new TcpListener(IPAddress.Loopback, 0);
			listener.Start(5);
			var ep = (IPEndPoint)listener.LocalEndpoint;

			Console.WriteLine("Server> waiting for accept");

			listener.BeginAcceptTcpClient((IAsyncResult ar) =>
			{
				var client = listener.EndAcceptTcpClient(ar);

				var sslStream = new SslStream(client.GetStream(), false);
				Console.WriteLine("Server> authenticate");

				sslStream.BeginAuthenticateAsServer(_ctx.ServerCertificate, async (ar2) =>
				{
					sslStream.EndAuthenticateAsServer(ar2);

					Console.WriteLine("Server> CurrentCipher: {0}", sslStream.Ssl.CurrentCipher.Name);
					Assert.AreEqual("AES256-GCM-SHA384", sslStream.Ssl.CurrentCipher.Name);

					var buf = new byte[256];
					await sslStream.ReadAsync(buf, 0, buf.Length);
					Assert.AreEqual(clientMessage.ToString(), buf.ToString());

					await sslStream.WriteAsync(serverMessage, 0, serverMessage.Length);

					sslStream.Close();
					client.Close();

					Console.WriteLine("Server> done");
				}, null);
			}, null);

			var evtDone = new AutoResetEvent(false);

			var tcp = new TcpClient(AddressFamily.InterNetwork);
			tcp.BeginConnect(ep.Address.ToString(), ep.Port, (IAsyncResult ar) =>
			{
				tcp.EndConnect(ar);

				var sslStream = new SslStream(tcp.GetStream());
				Console.WriteLine("Client> authenticate");

				sslStream.BeginAuthenticateAsClient("localhost", async (ar2) =>
				{
					sslStream.EndAuthenticateAsClient(ar2);

					Console.WriteLine("Client> CurrentCipher: {0}", sslStream.Ssl.CurrentCipher.Name);
					Assert.AreEqual("AES256-GCM-SHA384", sslStream.Ssl.CurrentCipher.Name);

					await sslStream.WriteAsync(clientMessage, 0, clientMessage.Length);

					var buf = new byte[256];
					await sslStream.ReadAsync(buf, 0, buf.Length);
					Assert.AreEqual(serverMessage.ToString(), buf.ToString());

					sslStream.Close();
					tcp.Close();

					Console.WriteLine("Client> done");

					evtDone.Set();
				}, null);
			}, null);

			evtDone.WaitOne();
		}
예제 #14
0
        static IEnumerator<Int32> Server(AsyncEnumerator ae, ServerState server)
        {
            var sleeper = new CountdownTimer();
            var settings = server.settings;
            var ipe = new IPEndPoint(IPAddress.Parse(settings.addressforward), settings.portforward);
            var serverSock = new TcpListener(IPAddress.Parse(settings.addresslisten), settings.portlisten);
            serverSock.Start(20);

            Console.WriteLine("Server started");
            Console.WriteLine("Listening on {0}:{1}", settings.addresslisten, settings.portlisten);
            Console.WriteLine("Forwarding to {0}:{1}", settings.addressforward, settings.portforward);
            while (true)
            {
                serverSock.BeginAcceptTcpClient(ae.End(), null);
                yield return 1;

                TcpClient local = null;
                try
                {
                    local = serverSock.EndAcceptTcpClient(ae.DequeueAsyncResult());
                    local.NoDelay = true;
                    local.LingerState.Enabled = false;
                }
                catch (SocketException)
                {
                    Console.WriteLine("A client failed to connect");
                }

                if(local != null)
                {
                    // handle client
                    var localAe = new AsyncEnumerator();
                    localAe.BeginExecute(ServerConnectRemote(localAe, server, ipe, local), localAe.EndExecute, localAe);
                }
            }
        }
예제 #15
0
        private void EstablishConnection(int listenPort, CancellationToken token)
        {
            // listen and accept
            listener = new TcpListener(IPAddress.Any, listenPort);
            token.ThrowIfCancellationRequested();

            TcpClient client;
            try {
                IsListening = true;
                listener.Start();

                // can be refactored. extract a static method.
                var ar = listener.BeginAcceptTcpClient(null, null);
                WaitUntilCompleted(ar, NetworkPollingInterval, token);
                token.ThrowIfCancellationRequested();
                client = listener.EndAcceptTcpClient(ar);
            }
            finally {
                listener.Stop();
                IsListening = false;
                token.ThrowIfCancellationRequested();
            }

            // get network stream.
            var ns = client.GetStream();
            ns.ReadTimeout = NetworkTimeOut;
            ns.WriteTimeout = NetworkTimeOut;
            networkStream = ns;

            IsNetworkConnected = true;
            token.ThrowIfCancellationRequested();
        }
예제 #16
0
        private static WindowsIdentity LogonUserTCPListen(string userName, string domain, string password)
        {
            // need a full duplex stream - loopback is easiest way to get that
            TcpListener tcpListener = new TcpListener(IPAddress.Loopback, 0);
            tcpListener.Start();
            ManualResetEvent done = new ManualResetEvent(false);

            WindowsIdentity id = null;
            tcpListener.BeginAcceptTcpClient(delegate(IAsyncResult asyncResult)
            {
                try
                {
                    using (NegotiateStream serverSide = new NegotiateStream(
                         tcpListener.EndAcceptTcpClient(asyncResult).GetStream()))
                    {
                        serverSide.AuthenticateAsServer(CredentialCache.DefaultNetworkCredentials,
                             ProtectionLevel.None, TokenImpersonationLevel.Impersonation);
                        id = (WindowsIdentity)serverSide.RemoteIdentity;
                    }
                }
                catch
                { id = null; }
                finally
                { done.Set(); }
            }, null);

            using (NegotiateStream clientSide = new NegotiateStream(new TcpClient("localhost",
                 ((IPEndPoint)tcpListener.LocalEndpoint).Port).GetStream()))
            {
                try
                {
                    clientSide.AuthenticateAsClient(new NetworkCredential(userName, password, domain),
                     "", ProtectionLevel.None, TokenImpersonationLevel.Impersonation);
                }
                catch
                { id = null; }//When the authentication fails it throws an exception
            }
            tcpListener.Stop();
            done.WaitOne();//Wait until we really have the id populated to continue
            return id;
        }
예제 #17
0
파일: Program.cs 프로젝트: xcjs/u413
        public static void DoBeginAcceptTcpClient(TcpListener listener)
        {
            listener.BeginAcceptTcpClient(x =>
            {
                var newClient = listener.EndAcceptTcpClient(x);
                string ipaddress = newClient.Client.RemoteEndPoint.ToString();
                Console.WriteLine(ipaddress + " has connected.");
                DoBeginAcceptTcpClient(listener);
                new Thread(() =>
                    {
                        string clientName = ipaddress;
                        string _username = null;
                        CommandContext _commandContext = null;
                        TerminalApi _terminalApi;
                        bool _appRunning = true;
                        bool _passwordField = false;

                        var stream = newClient.GetStream();
                        var streamReader = new StreamReader(stream);
                        var streamWriter = new StreamWriter(stream);
                        streamWriter.AutoFlush = true;
                        streamWriter.WriteLine("Welcome to the U413 telnet server.");

                        Action<string> invokeCommand = commandString =>
                            {
                                var kernel = new StandardKernel(new U413Bindings(false));
                                _terminalApi = kernel.Get<TerminalApi>();
                                _terminalApi.Username = _username;
                                _terminalApi.CommandContext = _commandContext;

                                streamWriter.WriteLine("Loading...");

                                var commandResult = _terminalApi.ExecuteCommand(commandString);

                                // Set the terminal API command context to the one returned in the result.
                                _commandContext = commandResult.CommandContext;

                                // If the result calls for the screen to be cleared, clear it.
                                if (commandResult.ClearScreen)
                                    for (int count = 0; count <= 25; count++)
                                        streamWriter.WriteLine();

                                // Set the terminal API current user to the one returned in the result and display the username in the console title bar.
                                _username = commandResult.CurrentUser != null ? commandResult.CurrentUser.Username : null;
                                //Console.Title = commandResult.TerminalTitle;

                                // Add a blank line to the console before displaying results.
                                if (commandResult.Display.Count > 0)
                                    streamWriter.WriteLine();

                                // Iterate over the display collection and perform relevant display actions based on the type of the object.
                                foreach (var displayItem in commandResult.Display)
                                {
                                    if ((displayItem.DisplayMode & DisplayMode.Parse) != 0)
                                        displayItem.Text = U413.Domain.Utilities.BBCodeUtility.ConvertTagsForConsole(displayItem.Text);

                                    streamWriter.WriteLine(displayItem.Text);
                                }
                                streamWriter.WriteLine();

                                //if (!commandResult.EditText.IsNullOrEmpty())
                                //    SendKeys.SendWait(commandResult.EditText.Replace("\n", "--"));

                                // If the terminal is prompting for a password then set the global PasswordField bool to true.
                                _passwordField = commandResult.PasswordField;

                                // If the terminal is asking to be closed then kill the runtime loop for the console.
                                _appRunning = !commandResult.Exit;
                            };

                        invokeCommand("INITIALIZE");
                        streamWriter.Write("> ");
                        while (!streamReader.EndOfStream)
                        {
                            var commandString = streamReader.ReadLine();
                            Console.WriteLine("{0}: {1}", (_username ?? clientName), commandString);
                            invokeCommand(commandString);
                            streamWriter.Write("> ");
                        }
                    }).Start();
            }, null);
        }
예제 #18
0
 private void AcceptClients()
 {
     try
     {
         this.listener = new TcpListener(IPAddress.Any, TcpClientReceivePort);
         this.listener.Start();
         this.listener.BeginAcceptTcpClient((IAsyncResult ar)=> 
         {
             try
             {
                 var tcpClient = listener.EndAcceptTcpClient(ar);
                 var client = new Client(this, tcpClient);
                 this.AddClient(client);
             }
             catch (Exception ex)
             {
                 MessageBox.Show(ex.Message);
             }
         }, null);
     }
     catch (Exception ex)
     {
         MessageBox.Show(ex.Message);
     }
 }
예제 #19
0
파일: Client.cs 프로젝트: samuto/Grevit
        /// <summary>
        /// Handle an incoming connection
        /// </summary>
        private void HandleRecieve(IAsyncResult result, TcpListener listener)
        {
            // Print debug message waiting for data
            AppendDebugListMessage("Waiting for data.");

            // Interrupt this process once stop listenening is true
            if (StopListening) return;

                // Accept connection
                using (TcpClient client = listener.EndAcceptTcpClient(result))
                {
                    client.NoDelay = true;

                    // Get the data stream ftom the tcp client
                    using (NetworkStream stream = client.GetStream())
                    {
                        using (StreamReader reader = new StreamReader(stream))
                        {
                            using (StreamWriter writer = new StreamWriter(stream))
                            {
                                writer.AutoFlush = true;

                                // read data from sender
                                string data = reader.ReadLine();

                                // write the line to the console
                                Console.WriteLine(data);

                                // Send the received data back to the sender
                                // in Order to make sure we recieved the
                                // right amount and correct data.
                                writer.WriteLine(data);

                                // Send our Categories, Families and Types to Grasshopper
                                writer.WriteLine(FamiliesToRespond);

                                // if there is some useful data
                                if (data != null && data.Length > 5)
                                {
                                    // Set the debugger message
                                    AppendDebugListMessage("Received " + data.Length + " Bytes.");

                                    // Deserialize the received data string
                                    Grevit.Types.ComponentCollection cc = StringToComponents(data);

                                    // If anything useful has been deserialized
                                    if (cc != null && cc.Items.Count > 0)
                                    {
                                        // Add Component collection to the client static component collection
                                        AddComponents(cc);

                                        // print another debug message about the component received
                                        AppendDebugListMessage("Translated " + cc.Items.Count.ToString() + " components.");

                                        // set stop listening switch
                                        StopListening = true;
                                    }

                                }

                            }

                        }
                    }


                }

            // If stop listening is set stop all listening processes
            if (StopListening)
            {
                // Stop the listener
                listener.Server.Close();
                listener.Stop();

                // Wait until processes are stopped
                Thread.Sleep(2000);

                // close the dialog automatically
                this.DialogResult = System.Windows.Forms.DialogResult.OK;
                this.Close();
            }

        }
예제 #20
0
 protected override StreamConnection DoConnect(Uri source)
 {
     TcpClient client = null;
       var bind_addr = GetBindAddress(source);
       if (bind_addr==null) {
     throw new BindErrorException(String.Format("Cannot resolve bind address: {0}", source.DnsSafeHost));
       }
       var listener = new TcpListener(IPAddress.Any, 1935);
       try {
     listener.Start(1);
     Logger.Debug("Listening on {0}", bind_addr);
     var ar = listener.BeginAcceptTcpClient(null, null);
     WaitAndProcessEvents(ar.AsyncWaitHandle, stopped => {
       if (ar.IsCompleted) {
     client = listener.EndAcceptTcpClient(ar);
       }
       return null;
     });
     Logger.Debug("Client accepted");
       }
       catch (SocketException) {
     throw new BindErrorException(String.Format("Cannot bind address: {0}", bind_addr));
       }
       finally {
     listener.Stop();
       }
       if (client!=null) {
     this.client = client;
     return new StreamConnection(client.GetStream(), client.GetStream());
       }
       else {
     return null;
       }
 }