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


C# TcpListener.AcceptTcpClient方法代码示例

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


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

示例1: Start

        public void Start()
        {
            // Создаем "слушателя" для указанного порта
            Listener = new TcpListener(IPAddress.Any, port);
            Listener.Start(); // Запускаем его
            //Client client = new Client(Listener.AcceptTcpClient());

            // В бесконечном цикле
            while (true)
            {
                Client client = new Client(Listener.AcceptTcpClient());
                ThreadPool.QueueUserWorkItem(new WaitCallback(ClientThread), Listener.AcceptTcpClient());
                if (client.GetSecondParam() != null)
                {
                    JobID jId = new JobID(jobIdCount, client.GetFirstParam(), client.GetSecondParam());
                    jobIdCount++;
                    jobId.Add(jId);
                }
                if (client.GetSecondParam() == null)
                {
                    jid = client.GetFirstParam();
                }
                Thread.Sleep(1000);
                Worker worker = new Worker(jobId, jid);
                Thread worker_thread = new Thread(worker.Start);
                worker_thread.Start();
            }
        }
开发者ID:Sleeper3345,项目名称:pure-csharp,代码行数:28,代码来源:Program.cs

示例2: ProcessMsBuildLoggerMessage

 public void ProcessMsBuildLoggerMessage(ConcurrentQueue<MessageArgsLogger> messagesToBeSend, IpAddressSettings settings)
 {
     TcpListener agentMsBuildListener = null;
     TcpClient agentTcpMsbuildReader = null;
     try
     {
         agentMsBuildListener = new TcpListener(settings.GetIPAddress(), settings.Port);
         agentMsBuildListener.Server.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, 1);
         agentTcpMsbuildReader = default(TcpClient);
         agentMsBuildListener.Start();
           agentTcpMsbuildReader = agentMsBuildListener.AcceptTcpClient();
         do
         {
             string dataFromClient = ATACore.TcpWrapperProcessor.TcpClientWrapper.ReadSimpleClientMessage(agentTcpMsbuildReader);
             if (!String.IsNullOrEmpty(dataFromClient))
                 ATACore.CommandExecutor.EnqueueNewMessage(dataFromClient, MessageSource.MsBuildLogger, messagesToBeSend);
             else if (dataFromClient == null)
                 agentTcpMsbuildReader = agentMsBuildListener.AcceptTcpClient();
         } while (true);
     }
     catch (Exception ex)
     {
         Log.Error("Exception in ProcessClientMessge", ex);
     }
     finally
     {
         ATACore.TcpWrapperProcessor.TcpListenerWrapper.CloseTcpMsLogger(agentMsBuildListener, agentTcpMsbuildReader);
     }
 }    
开发者ID:kennedykinyanjui,项目名称:Projects,代码行数:29,代码来源:TcpMsBuildLoggerProcessor.cs

示例3: ReceiveActions

        public void ReceiveActions()
        {
            try
            {
                serversocket = new TcpListener(new IPEndPoint(IPAddress.Any, 1234));
                serversocket.Start();

                tcpP1 = serversocket.AcceptTcpClient();
                NetworkStream P1stream = tcpP1.GetStream();
                InstancierBateaux(p1, P1stream);
                WriteMessage("Premier Joueur accepté");

                tcpP2 = serversocket.AcceptTcpClient();
                NetworkStream P2stream = tcpP2.GetStream();
                InstancierBateaux(p2, P2stream);
                WriteMessage("Deuxième Joueur accepté");

                WriteMessage("Tous les bateaux sont prêts");

                while (!end)
                {
                    ReceiveAttack(p1, P2stream, P1stream);
                    ReceiveAttack(p2, P1stream, P2stream);
                }
            }
            catch(Exception se)
            {
                MessageBox.Show(se.Message + " Vous avez perdu le contact avec un socket!");
            }
        }
开发者ID:PoneyLoverXz,项目名称:Battleship,代码行数:30,代码来源:Serveur.cs

示例4: Run

        public void Run()
        {
            Thread read = new Thread(Reader);
            read.IsBackground = true;

            TcpListener listen = new TcpListener(IPAddress.Parse("127.0.0.1"), 36345);
            listen.Start();

            Thread.Sleep(100);
            read.Start();

            var client = listen.AcceptTcpClient();

            byte[] data = new byte[154600];
            Stopwatch sw = new Stopwatch();

            var stream = client.GetStream();

            sw.Start();
            for (int x = 0; x < Loop; x++)
                stream.Write(data, 0, data.Length);
            sw.Stop();
            stream.Close();

            Console.WriteLine("Write: " + ((Loop * data.Length) / sw.Elapsed.TotalSeconds / 1000000).ToString());
            Thread.Sleep(1000);

            read.Join();
        }
开发者ID:GridProtectionAlliance,项目名称:openHistorian,代码行数:29,代码来源:BenchmarkSockets.cs

示例5: StopTcpListener

 public void StopTcpListener ()
 {
     var listener = new TcpListener (IPAddress.Loopback, 0);
     listener.Start ();
     listener.Stop ();
     Assert.Throws<InvalidOperationException> (() => listener.AcceptTcpClient ());
 }
开发者ID:paperclip,项目名称:krpc,代码行数:7,代码来源:AssumptionsTest.cs

示例6: 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

示例7: button2_Click

        private void button2_Click(object sender, EventArgs e)
        {
            TcpListener serverSocket = new TcpListener(IPAddress.Any, 4955);
           
            TcpClient clientSocket = default(TcpClient);
            serverSocket.Start();
            
            clientSocket = serverSocket.AcceptTcpClient();
            

            try
            {
                
                NetworkStream networkStream = clientSocket.GetStream();
                byte[] bytesFrom = new byte[10025];
                networkStream.Read(bytesFrom, 0, (int)clientSocket.ReceiveBufferSize);
                string dataFromClient = System.Text.Encoding.ASCII.GetString(bytesFrom);
                dataFromClient = dataFromClient.Substring(0, dataFromClient.IndexOf("$"));
                MessageBox.Show( dataFromClient);
                
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.ToString());
            }
        }
开发者ID:ptchankue,项目名称:mimi,代码行数:26,代码来源:frmNetwork.cs

示例8: Program

        Program()
        {
            IPAddress ip = Info.GetIp();
            TcpListener listener = new TcpListener(ip,Info.Port);
            storage = new DataStorage();
            listener.Start();
            int counter = 0;
            Console.WriteLine("Server started: {0}",DateTime.Now);
            Console.WriteLine("Server ip: {0}", ip);
            Console.WriteLine("Server port: {0}",Info.Port);

            while (true)
            {
                TcpClient newClient = listener.AcceptTcpClient();
                if (!IsMonitor(newClient))
                {
                    counter++;
                    Console.WriteLine("is client");
                    Client client = new Client(newClient, this, counter, storage);
                    clients.Add(client);
                }
                else if (_monitor != null)
                {
                    if (!_monitor.TcpClient.Connected)
                    {
                        _monitor = new Monitor(newClient,this,clients, storage);
                    }
                }
                else
                {
                    _monitor = new Monitor(newClient,this,clients, storage);
                }
            }
        }
开发者ID:projectgroepA1,项目名称:ProjectgroepA1,代码行数:34,代码来源:Program.cs

示例9: Start

        public void Start()
        {
            try
            {
                listener = new TcpListener(IPAddress.Parse(ServerIP), ServerPort);
                listener.Start();

                while (running)
                {
                    TcpClient client = null;
                    try
                    {
                        client = listener.AcceptTcpClient();
                        Console.WriteLine("AudioServer Accept");
                        new Thread(new AudioSender(client.GetStream()).Start).Start();
                    }
                    catch (Exception)
                    {
                        if (client != null)
                            client.Close();
                    }
                }

                Console.WriteLine("AudioServer Done");

            }
            catch (Exception)
            {

            }
        }
开发者ID:ZhuGongpu,项目名称:CloudX,代码行数:31,代码来源:AudioServer.cs

示例10: Run

 /// <summary>
 ///  Thread for session with PythonServer
 /// </summary>
 private void Run()
 {
     try
     {
         // Build listener for python engine
         listener = new TcpListener(9669);
         listener.Start();
         //  Wait connection from python engine and if successful then create new socket to python engine
         pythonClient = listener.AcceptTcpClient();
         mainForm.PrintToLog(DateTime.Now.ToShortTimeString() + " :  Server trying start...", Color.Black);
         listener.Stop(); // stop listening because python engine connected to GUI
         flagRun = true;
         // Asynchronic StateObject
         StateObject stateObject = new StateObject();
         stateObject.workSocket = pythonClient.Client;
         // Begins to asynchronously receive data from a connected socket with  python engine
         pythonClient.Client.BeginReceive(stateObject.buffer, 0, StateObject.BufferSize, 0, new AsyncCallback(Read_Callback), stateObject);
     }
     catch (SocketException se)
     {
         mainForm.PrintToLog(se.Message, Color.Red);
     }
     catch (Exception e)
     {
         mainForm.PrintToLog(e.Message, Color.Red);
     }
 }
开发者ID:zadatal,项目名称:Parent-protection,代码行数:30,代码来源:PythonHandler.cs

示例11: waitForClients

        public void waitForClients()
        {
            // create network Socket (winsok)
            //TODO : basculer Socket dans socketManager prévu à cet effet.
            //TODO : enlever valeurs par défaut et passer paramètres depuis main
            IPAddress ipaddress = new IPAddress(new byte[] { 127, 0, 0, 1 });
            TcpListener tcpl = new TcpListener(ipaddress, 2106);
            tcpl.Start();
            while (_serverRunning)
            {

                Display.displayMessage("Thread tourne.");
                TcpClient tcpC = tcpl.AcceptTcpClient();
                if (tcpC.Connected)
                {
                    Display.displayMessage("Client connecté !! ");
                    Display.displayMessage("Address : " + tcpC.Client.RemoteEndPoint.ToString());

                    // Create Thread for its process.

                    Thread playerHandler = new Thread(new ParameterizedThreadStart(handleIncomingClient));
                    playerHandler.Start(tcpC);

                }
            }

            Thread.Sleep(100);
        }
开发者ID:xNexus9,项目名称:tabula-rasa-server-emulator,代码行数:28,代码来源:ThreadManager.cs

示例12: run

        public void run()
        {
            IPAddress localAdd = IPAddress.Parse(StarryboundServer.config.proxyIP);
            TcpListener serversocket = new TcpListener(localAdd, StarryboundServer.config.proxyPort);

            serversocket.Start();
            StarryboundServer.logInfo("Proxy server has been started on " + localAdd.ToString() + ":" + StarryboundServer.config.proxyPort);
            StarryboundServer.serverState = ServerState.Running;

            try
            {
                while (true)
                {
                    TcpClient clientSocket = serversocket.AcceptTcpClient();
                    new Thread(new ThreadStart(new ClientThread(clientSocket).run)).Start();
                }
            }
            catch (Exception e)
            {
                StarryboundServer.logException("ListenerThread: " + e.ToString());
            }

            serversocket.Stop();
            StarryboundServer.logException("ListenerThread has failed - No new connections will be possible.");
            Console.ReadLine();
        }
开发者ID:Gremlin13,项目名称:StarryboundServer,代码行数:26,代码来源:ListenerThread.cs

示例13: ServerCore

        private ServerCore()
        {
            LoadConfig();
            RegisterCommanders();
            try
            {
                sqlConnecter = SqlConnector.Instance;
            }
            catch (Exception ex)
            {
                Console.WriteLine("Could not connect to Mysql: \"" + ex.Message + "\"");
                Console.WriteLine("Aborting. Press any key to exit");
                Console.Read();
                return;
            }
            idConnection = new Dictionary<UInt32, TcpClient>();
            connectionWorker = new Dictionary<TcpClient, ClientWorker>();
            connectionId = new Dictionary<TcpClient, UInt32>();
            workers = new List<ClientWorker>();
            TcpListener tcpListener = new System.Net.Sockets.TcpListener(IPAddress.Parse(ip), port);

            tcpListener.Start();
            while (true)
            {
                TcpClient connection = tcpListener.AcceptTcpClient();
                Console.WriteLine("Someone connected");
                ClientWorker worker = new ClientWorker(connection);
                lock (mutex)
                {
                    connectionWorker.Add(connection, worker);
                    workers.Add(worker);
                }
            }
        }
开发者ID:dianatatu,项目名称:REACH,代码行数:34,代码来源:ServerCore.cs

示例14: Main

        public static void Main(string[] args)
        {
            IPAddress ip = IPAddress.Loopback;
            int port = 9000;

            byte[] buffer = new byte[256];

            TcpListener server = new TcpListener (ip, port);
            try {
                server.Start ();

                while (true) {
                    Console.WriteLine ("waiting for connection");
                    TcpClient client = server.AcceptTcpClient ();
                    Console.WriteLine ("connected " + client.Client.AddressFamily);

                    NetworkStream stream = client.GetStream ();

                    // receive data from client, send responses
                    int i;
                    while ((i = stream.Read (buffer, 0, buffer.Length)) != 0) {
                        HandleMessage (buffer, i);
                        SendResponse (stream, "response");
                    }
                }
            } catch (SocketException e) {
                Console.WriteLine ("SocketException: {0}", e);
            } finally {
                server.Stop ();
            }
        }
开发者ID:mstevenson,项目名称:Aurelius,代码行数:31,代码来源:Program.cs

示例15: Main

        public static void Main(string[] args)
        {
            chatrooms = new List<Chatroom> ();
            users = new List<User> ();

            Console.WriteLine ("Please enter the port for the server: ");
            string port = Console.ReadLine ();

            TcpListener serverSocket = new TcpListener (IPAddress.Loopback, Convert.ToInt32 (port));

            try {
                serverSocket.Start ();
                Console.WriteLine (String.Format ("[Server started on 127.0.0.1 {0}]", port));
            } catch {
                Console.WriteLine ("[Server failed to start]");
                return;
            }

            int clientIds = 1;

            // create a new client when a new connection comes in, and create user entry for that client connection
            while (true)
            {
                TcpClient client = serverSocket.AcceptTcpClient ();
                User user = new User (client, clientIds);
                users.Add (user);
                clientIds++;
                Thread t = new Thread (new ParameterizedThreadStart (HandleClient));
                t.Start (user);
            }
        }
开发者ID:taylor-x,项目名称:436-A1-Server,代码行数:31,代码来源:Program.cs


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