当前位置: 首页>>代码示例>>C#>>正文


C# TcpListener.Pending方法代码示例

本文整理汇总了C#中System.Net.Sockets.TcpListener.Pending方法的典型用法代码示例。如果您正苦于以下问题:C# TcpListener.Pending方法的具体用法?C# TcpListener.Pending怎么用?C# TcpListener.Pending使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在System.Net.Sockets.TcpListener的用法示例。


在下文中一共展示了TcpListener.Pending方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。

示例1: ChatServer

        public ChatServer()
        {
            // create nickName & nickNameByConnect variables
            nickName = new Hashtable(100);
            nickNameByConnect = new Hashtable(100);

            // initialise chatServer with at the local IP address host on port 4296
            chatServer = new TcpListener(host, 4296);
            // check to see that the server is running

            // visual indication server is running
            Console.WriteLine("Server Running");

            //keep running
            while (true)
            {
                // start the server
                chatServer.Start();

                // if there are connections pending
                if (chatServer.Pending())
                {
                    // accept the connection
                    Chat.Sockets.TcpClient chatConnection = chatServer.AcceptTcpClient();
                    // display message to client
                    Console.WriteLine("You are now connected");
                    // create a new DoCommunicate object
                    DoCommunicate comm = new DoCommunicate(chatConnection);
                }
            }
        }
开发者ID:DerailedJeff,项目名称:ChatServer,代码行数:31,代码来源:ChatServer.cs

示例2: AddClients

        /// <summary>
        /// This method will constantly run as a thread. It currently sends a multicast to the network every second, informing
        /// computers on the network that it is there. When a client sees this, it will send a message to the server and the client
        /// will be added to the clients list.
        /// </summary>
        public static void AddClients()
        {
            clients = new List<ClientThread>();
            TcpListener serverSocket = new TcpListener(IPAddress.Any, 8888);
            serverSocket.Start();

            while (true)
            {
                TcpClient tempClientSocket = new TcpClient();
                tempClientSocket.ReceiveTimeout = 300;

                SendMulticast();

                //Check and see if a computer is trying to connect.
                //If not, then sleep, and resend multicast in a second
                if (serverSocket.Pending())
                {
                    tempClientSocket = serverSocket.AcceptTcpClient();
                    ClientThread c = new ClientThread(tempClientSocket,null);
                    clients.Add(c);
                    Console.WriteLine("Connected to " + c.GetClientIP() + " :: "+c.GetPort());
                }
                else {
                    Thread.Sleep(1000); //Sleep for a second, before sending the next multicast.
                }
            }
        }
开发者ID:GavinKenna,项目名称:Muroidea,代码行数:32,代码来源:Program.cs

示例3: NoChannelForkGroup

        public void NoChannelForkGroup()
        {
            using (ShortcutTestClass shortcutTestClass = ParallelizationFactory.GetParallelized<ShortcutTestClass>())
            {
                TcpListener tcpListener = new TcpListener(IPAddress.Loopback, 23000);
                tcpListener.Start();

                shortcutTestClass.NoChannelForkGroup("Test");

                int i = 0;
                while (!tcpListener.Pending())
                {
                    Thread.Sleep(100);
                    if (i++ > 20)
                    {
                        tcpListener.Stop();
                        throw new TimeoutException();
                    }
                }

                TcpClient tcpClient = tcpListener.AcceptTcpClient();
                Expect(new StreamReader(tcpClient.GetStream()).ReadToEnd(), EqualTo("Test"));

                tcpClient.Close();
                tcpListener.Stop();
            }
        }
开发者ID:Noah1989,项目名称:fmacj,代码行数:27,代码来源:ShortcutTest.cs

示例4: Main

        static void Main(string[] args)
        {
            var settings = ConfigurationManager.AppSettings;
            var port = settings["COM_PORT"];
            var speed = Convert.ToInt32(settings["COM_SPEED"]);
            var tcpPort = Convert.ToInt32(settings["TCP_PORT"]);
            serial = new SerialManager(port, speed);
            Console.WriteLine("UART: " + port + " - " + speed);
            server = new HardwareTcpServer(tcpPort);
            server.OnServerState += server_OnServerState;
            server.OnClientState += server_OnClientState;
            server.OnData += server_OnData;
            serial.OnReceive += serial_OnReceive;
            serial.OnStateChange += serial_OnStateChange;
            serial.Connect();

           // bridge = new HttpToUartBridge(6200);

            TcpListener listener = new TcpListener(IPAddress.Parse("188.127.233.35"), tcpPort);
            listener.Start();
            Console.WriteLine("TCP: " + tcpPort);
            while (Thread.CurrentThread.ThreadState == ThreadState.Running)
            {
                Console.WriteLine("Listening " + tcpPort);
                while (!listener.Pending())
                {
                    Thread.Sleep(300);
                }
                server.AcceptTcpClient(listener.AcceptSocket());
            }
            Console.WriteLine("Stopped");
            listener.Stop();
            server.Close();
            serial.Close();
        }
开发者ID:WebManufacture,项目名称:Legacy.NET,代码行数:35,代码来源:Program.cs

示例5: Listen

        private void Listen()
        {
            TcpListener tcpListener = new TcpListener(IPAddress.Any, ListenPort);
            tcpListener.Start();
            TcpClient client = null;
            try
            {
                while (!CloseClass)
                {
                    if (!tcpListener.Pending())
                    {
                        Thread.Yield();
                    }
                    else
                    {
                        client = tcpListener.AcceptTcpClient();
                        ThreadPool.QueueUserWorkItem(x => returnMethod(client));
                    }
                }
            }
            finally
            {
                if (client != null)
                {
                    client.Close();
                }

                tcpListener.Stop();
            }
        }
开发者ID:Siryu,项目名称:Distributed-Processing-Capstone,代码行数:30,代码来源:RemoteServer.cs

示例6: StartThread

 public void StartThread()
 {
     Print("Server started");
     var listner=new TcpListener(IPAddress.Any, port);
     listner.Start();
     CvarcClient cvarcClient = null;
     while(true)
     {
         while (!listner.Pending())
         {
             if (exitRequest)
             {
                 if (cvarcClient != null)
                     cvarcClient.Close();
                 listner.Stop();
                 return;
             }
             Thread.Sleep(1);
         }
         var client = listner.AcceptTcpClient();
         Print("Client accepted");
         if (cvarcClient != null)
             cvarcClient.Close(); // этот метод должен внутри CvarcClient устанавливать флаг, при котором цикл внутри Read заканчивается исключением
         cvarcClient = new CvarcClient(client);
         if (ClientConnected != null)
             ClientConnected(cvarcClient);
     }
 }
开发者ID:mrkvinter,项目名称:CVARC-Unity,代码行数:28,代码来源:PercistentTCP.cs

示例7: Chatserver

 public Chatserver()
 {
     //create our nickname and nickname by connection variables
         nickName = new Hashtable(100);
         nickNameByConnect = new Hashtable(100);
         //create our TCPListener object
         chatServer = new System.Net.Sockets.TcpListener(4296);
         //check to see if the server is running
         //while (true) do the commands
         while (true)
         {
             //start the chat server
             chatServer.Start();
             //check if there are any pending connection requests
             if (chatServer.Pending())
             {
                  //if there are pending requests create a new connection
                 Chat.Sockets.TcpClient chatConnection = chatServer.AcceptTcpClient();
                 //display a message letting the user know they're connected
                 Console.WriteLine("You are now connected");
                 //create a new DoCommunicate Object
                 DoCommunicate comm = new DoCommunicate(chatConnection);
             }
         }
 }
开发者ID:jchild,项目名称:Fear_is_Crisp,代码行数:25,代码来源:Chatserver.cs

示例8: run

 public void run()
 {
     Debug.Log("ACCEPTOR THREAD: Starting Tcp Listener");
     try
     {
         tcpListener = new TcpListener(IPAddress.Any, 4444);
         tcpListener.Start ();
         //new Thread (new ThreadStart (DiscoveryThread.Instance.run)).Start();
         Debug.Log("ACCEPTOR THREAD: Waiting for clients...");
         while (_isRunning) {
             while (!tcpListener.Pending()) {
                 Thread.Sleep (1000);
             }
             Debug.Log("ACCEPTOR THREAD: Client accepted!");
             ConnectionThread newconnection = new ConnectionThread(tcpListener);
             runningConnections.Add(newconnection);
             new Thread (new ThreadStart (newconnection.HandleConnection)).Start();
             Thread.Sleep(100);
         }
     }
     catch (Exception e)
     {
         Debug.LogError (e.ToString());
     }
     Debug.Log("ACCEPTOR THREAD: TCP Requesting Stop from " + runningConnections.Count + " open connections");
     foreach (ConnectionThread connection in runningConnections) {
         connection.RequestStop();
     }
     Debug.Log("ACCEPTOR THREAD: Ending...");
 }
开发者ID:ami-bgu,项目名称:CoopWorld,代码行数:30,代码来源:ThreadedTcpSrvr.cs

示例9: Start

        public static void Start(int port)
        {
            TcpListener listener = new TcpListener (IPAddress.Loopback, port);
            listener.Start ();

            while (run) {
                while (!listener.Pending() && run) {
                    Thread.Sleep (200);
                }

                if (!run)
                    break;

                Socket newSocket = listener.AcceptSocket ();

                Thread thread = new Thread (new ParameterizedThreadStart (Handshaker));

                int id = 0;
                lock (serviceThreads) {
                    id = serviceThreads.Count > 0 ? serviceThreads.Keys.Max () + 1 : 0;
                    serviceThreads.Add (id, thread);
                }

                thread.Start (new object[] { id, newSocket });
            }
        }
开发者ID:xxtbg,项目名称:coredroidservice,代码行数:26,代码来源:SocketService.cs

示例10: ReceiveTCP

        public static void ReceiveTCP(int portN)
        {
            TcpListener Listener = null;
            try
            {
                Listener = new TcpListener(IPAddress.Any, portN);
                Listener.Start();
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
            int BufferSize = 4096;
            byte[] RecData = new byte[BufferSize];
            int RecBytes;

            for (; ; )
            {
                TcpClient client = null;
                NetworkStream netstream = null;
                //Status = string.Empty;
                try
                {
                    string message = "Accept the Incoming File ";
                    string caption = "Incoming Connection";
                    //MessageBoxButtons buttons = MessageBoxButtons.YesNo;
                    //DialogResult result;

                    if (Listener.Pending())
                    {
                        client = Listener.AcceptTcpClient();
                        netstream = client.GetStream();
                        //Status = "Connected to a client\n";
                        //result = MessageBox.Show(message, caption, buttons);
                        Console.WriteLine("Connected to a sender");
                        string dirPath = Environment.GetFolderPath(Environment.SpecialFolder.Desktop);
                        string SaveFileName = dirPath+"\\"+string.Format("RecvdFile-{0:yyyy-MM-dd_hh-mm-ss-tt}", DateTime.Now);
                            if (SaveFileName != string.Empty)
                            {
                                int totalrecbytes = 0;
                                FileStream Fs = new FileStream(SaveFileName, FileMode.OpenOrCreate, FileAccess.Write);
                                while ((RecBytes = netstream.Read(RecData, 0, RecData.Length)) > 0)
                                {
                                    Fs.Write(RecData, 0, RecBytes);
                                    totalrecbytes += RecBytes;
                                }
                                Fs.Close();
                            }
                            netstream.Close();
                            client.Close();

                    }
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex.Message);
                    //netstream.Close();
                }
            }
        }
开发者ID:anirudhranganath,项目名称:TCP-File-Stream,代码行数:60,代码来源:Program.cs

示例11: Listen

        public void Listen()
        {
            TcpListener listener = new TcpListener(IPAddress.Any,
                Convert.ToInt32(ConfigurationManager.AppSettings["tcpPort"]));
            try
            {
                listener.Start();
                int clientNr = 0;
                OnLogged("Waiting for a connection...");
                while (continueProcess)
                {
                    if (listener.Pending())
                    {
                        TcpClient handler = listener.AcceptTcpClient();

                        if (handler != null)
                        {
                            OnLogged("Client #{0} accepted", ++clientNr);

                            ClientHandler client = new ClientHandler(handler);
                            client.Logged += Logged;
                            connectionPool.Enqueue(client);
                        }
                    }

                    Thread.Sleep(100);
                }
            }
            finally
            {
                listener.Stop();
            }
        }
开发者ID:mtimmerman,项目名称:vikingwallet-pos,代码行数:33,代码来源:ClientService.cs

示例12: Replyer

        /// <summary>
        ///   Monitor pentru starea firului de execuţie de rezolvare a cererilor.
        /// </summary>
        //private ManualResetEvent tcpClientConnected;
        /// <param name="iTransformer">Transformatorul de cereri în răspuns</param>
        /// <param name="port">Portul pe care se ascultă</param>
        public Replyer(ITransformer iTransformer, int port)
        {
            this.iTransformer = iTransformer;

            TcpListener tcpl = new TcpListener(IPAddress.Any, port);

            tcpl.Start();

            while (true) {

                try {

                    while (!tcpl.Pending()) {

                        Thread.Sleep(1000);
                    }

                    TcpClient client = tcpl.AcceptTcpClient();

                    ThreadPool.QueueUserWorkItem(receiveTransformAndSendFeedback, client);
                }
                catch (ThreadAbortException) {

                    tcpl.Stop();

                    return;
                }
            }
        }
开发者ID:slung,项目名称:fuzzyselector,代码行数:35,代码来源:Replyer.cs

示例13: Listen

 public void Listen(int port)
 {
     TcpListener serverSocket = new TcpListener(IPAddress.Parse("127.0.0.1"), port);
     TcpClient clientSocket = default(TcpClient);
     serverSocket.Start();
     Console.WriteLine(" >> Server Started");
     try
     {
         while (true)
         {
             if (serverSocket.Pending())
             {
                 clientSocket = serverSocket.AcceptTcpClient();
                 ThreadPool.QueueUserWorkItem(o => ProcessRequest(clientSocket));
             }
             else
             {
                 Thread.Sleep(100);
             }
         }
     }
     catch (ThreadAbortException)
     {
         Console.WriteLine(" >> Server Ended");
         t = null;
     }
 }
开发者ID:pSasa,项目名称:c-,代码行数:27,代码来源:SocketLayer.cs

示例14: MassiveInvoke

        public void MassiveInvoke()
        {
            using (ChordTestClass chordTestClass = ParallelizationFactory.GetParallelized<ChordTestClass>())
            {
                List<TcpListener> tcpListeners = new List<TcpListener>();

                for (int i = 0; i < 500; i++)
                {
                    TcpListener tcpListener = new TcpListener(IPAddress.Loopback, 23000 + i);
                    tcpListeners.Add(tcpListener);
                    tcpListener.Start();
                    chordTestClass.TestMethod4(string.Format("V{0}", i));
                    chordTestClass.TestMethod5(i);
                }

                List<string> results = new List<string>();

                foreach (TcpListener tcpListener in tcpListeners)
                {
                    int i = 0;
                    var timeout = 10;
                    while (!tcpListener.Pending())
                    {
                        Thread.Sleep(100);
                        if (++i > timeout)
                        {
                            tcpListener.Stop();
                            throw new TimeoutException();
                        }
                    }

                    TcpClient tcpClient = tcpListener.AcceptTcpClient();
                    results.Add(new BinaryReader(tcpClient.GetStream()).ReadString());

                    tcpClient.Close();
                    tcpListener.Stop();
                }

                Debug.Print(string.Format("Received {0} results.", results.Count));

                List<string> results1 = new List<string>();
                List<string> results2 = new List<string>();

                foreach(string value in results)
                {
                    string[] values = value.Split(',');
                    results1.Add(values[0]);
                    results2.Add(values[1]);
                }

                for (int i = 0; i < 500; i++)
                {
                    Expect(results1.Contains(string.Format("V{0}", i)),
                           string.Format("Missing value1: {0}", i));
                    Expect(results2.Contains(string.Format("{0}", 23000 + i)),
                           string.Format("Missing value2: {0}", i));
                }

            }
        }
开发者ID:Noah1989,项目名称:fmacj,代码行数:60,代码来源:ChordTest.cs

示例15: Main

        static void Main(string[] args)
        {
            ServerConfig.ParseConfig(args);
            Logger.InitWithName(ServerConfig.Name);
            Thread.CurrentThread.Name = "SERVER";

            var slave = new TcpListener(ServerConfig.ListenPort);

            try
            {
                try
                {
                    slave.Start(10);
                }
                catch
                {
                    throw new Exception(@"Невозможно открыть сокет №" + ServerConfig.ListenPort.ToString());
                }

                while (true)
                {
                    TcpClient connect = null;
                    if (slave.Pending())
                    {
                        try
                        {
                            connect = slave.AcceptTcpClient();
                        }
                        catch
                        {
                        }
                    }

                    if (connect == null) {Thread.Sleep(500);  continue;}
                    if (connect.Connected)
                    {
                        Terminal terminal = new Terminal(connect);
                        Thread thread = new Thread(Terminal.DoWork);
                        thread.Start(terminal);
                    }
                    Thread.Sleep(0);
                }
            }
            catch (OutOfMemoryException e)
            {
                Logger.WriteMessage(Logger.EventID.ServiceCrash, @"ПЕРЕПОЛНЕНИЕ ВИРТУАЛЬНОЙ ПАМЯТИ: " + e.ToString());
            }
            catch (Exception ex)
            {
                Logger.WriteMessage(Logger.EventID.ServiceCrash, ex.ToString());
            }
            finally
            {
                slave.Stop();
                Logger.Close();
            }
        }
开发者ID:Minatron,项目名称:Minatron,代码行数:57,代码来源:Server.cs


注:本文中的System.Net.Sockets.TcpListener.Pending方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。