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


C# Sockets.TcpListener类代码示例

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


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

示例1: connect

 //Connect to the client
 public void connect()
 {
     if (!clientConnected)
     {
         IPAddress ipAddress = IPAddress.Any;
         TcpListener listener = new TcpListener(ipAddress, portSend);
         listener.Start();
         Console.WriteLine("Server is running");
         Console.WriteLine("Listening on port " + portSend);
         Console.WriteLine("Waiting for connections...");
         while (!clientConnected)
         {
             s = listener.AcceptSocket();
             s.SendBufferSize = 256000;
             Console.WriteLine("Connection accepted from " + s.RemoteEndPoint);
             byte[] b = new byte[65535];
             int k = s.Receive(b);
             ASCIIEncoding enc = new ASCIIEncoding();
             Console.WriteLine("Received:" + enc.GetString(b, 0, k) + "..");
             //Ensure the client is who we want
             if (enc.GetString(b, 0, k) == "hello" || enc.GetString(b, 0, k) == "hellorcomplete")
             {
                 clientConnected = true;
                 Console.WriteLine(enc.GetString(b, 0, k));
             }
         }
     }
 }
开发者ID:kartikeyadubey,项目名称:share,代码行数:29,代码来源:Server.cs

示例2: StartListening

        public void StartListening()
        {
            R = RowacCore.R;
            R.Log("[Listener] Starting TCP listener...");
            TcpListener listener = new TcpListener(IPAddress.Any, 28165);
            listener.Start();

            while (true)
            {
                try
                {
                    var client = listener.AcceptSocket();
            #if DEBUG
                    R.Log("[Listener] Connection accepted.");
            #endif

                    var childSocketThread = new Thread(() =>
                    {
                        byte[] data = new byte[1048576]; // for screenshots and tasklists
                        int size = 0;
                        while (client.Available != 0)
                            size += client.Receive(data, size, 256, SocketFlags.None); // TODO: increase reading rate from 256?
                        client.Close();

                        string request = Encoding.ASCII.GetString(data, 0, size);
            #if DEBUG
                        R.Log(string.Format("Received [{0}]: {1}", size, request));
            #endif
                        ParseRequest(request);
                    });
                    childSocketThread.Start();
                }
                catch (Exception ex) { R.LogEx("ListenerLoop", ex); }
            }
        }
开发者ID:Riketta,项目名称:rust-anticheat,代码行数:35,代码来源:Server.cs

示例3: ServerContext

        public ServerContext(int port, int maxclients, ref List<string> TextStack, string OwnIP)
        {
            BeginSendUdpServerCallback = new AsyncCallback(OnBeginSendUdpServerCallbackFinished);
            ServerMessage = System.Text.Encoding.ASCII.GetBytes("OK:" + OwnIP);

            UdpServer = new UdpClient(new IPEndPoint(IPAddress.Any, 8011)); //da bei xp fehler

            UdpServer.JoinMulticastGroup(BroadcastServer.Address);

            UdpServer.BeginSend(ServerMessage, ServerMessage.Length, BroadcastServer, BeginSendUdpServerCallback, null);

            MaxClients = maxclients;

            Ip = IPAddress.Any;
            this.Port = port;

            listener = new TcpListener(Ip, Port);
            Clients = new List<ClientContext>(MaxClients);

            listener.Start();

            BeginAcceptSocketCallback = new AsyncCallback(OnClientConnected);

            this.TextStack = TextStack;
        }
开发者ID:janis2013,项目名称:TextVerteilerServerDns,代码行数:25,代码来源:ServerContext.cs

示例4: FormServeur

 // constructeur
 public FormServeur()
 {
     InitializeComponent();
     Joueur1 = new Joueur(panelFond, new Point(100, 100),true);
     Joueur2 = new Joueur(panelFond, new Point(100, 150),false); // Cette fois les joueurs sont clairements
     labelScoreJ1.Text = "0";
     labelScoreJ2.Text = "0"; // L'interface n'est plus la même non plus, on dédouble tout.
     pBChargeJ1.Maximum = 1000;
     pBChargeJ1.Minimum = 0;
     pBChargeJ2.Maximum = 1000;
     pBChargeJ2.Minimum = 0;
     try
     {
         IPAddress ipAd = IPAddress.Parse("127.0.0.1"); //on utilise l'adresse ip locale
         myList = new TcpListener(ipAd, 8001);   //initialisation du listener
         myList.Start();                         // on écoute sur le port
         Console.WriteLine("The server is running at port 8001...");
         Console.WriteLine("The local End point is :" + myList.LocalEndpoint); // Ces trois lignes ci ne servent qu'a controler via la console ce qui se passe.
         Console.WriteLine("Waiting for a connection.....");
         cl = myList.AcceptTcpClient();          // dés qu'il y a une connection on peut passer a la suite
         Console.WriteLine("Connection accepted from " + cl.Client.RemoteEndPoint);
         stm = cl.GetStream(); // le flux de données est créé
      }
      catch (Exception e)
     {
         Console.WriteLine("Error..... " + e.StackTrace);
         Console.ReadLine();
     }
     th1 = new Thread(Launch); // on lance le thread qui va lire le flux
     th1.Name = "Serveur";
     th1.Start();
 }
开发者ID:Boucquey,项目名称:projetInfo,代码行数:33,代码来源:FormServeur.cs

示例5: TCPServer

 public TCPServer(int port)
 {
     listener = new TcpListener(IPAddress.Any, port);
     player = new AI(this);
     listener.Start();
     Start();
 }
开发者ID:Vin1000,项目名称:Galcon,代码行数:7,代码来源:TCPServer.cs

示例6: EmbeddedSmtpServer

        public EmbeddedSmtpServer(IPAddress address, int port = 25)
        {
            Address = address;
            Port = port;

            Listener = new TcpListener(Address, port);
        }
开发者ID:ahjohannessen,项目名称:EmbeddedMail,代码行数:7,代码来源:EmbeddedSmtpServer.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: Servidor

 public Servidor()
 {
     Console.WriteLine ("Iniciando servidor");
     ipAddress = Dns.GetHostEntry("localhost").AddressList[0];
     listener = new TcpListener (ipAddress, porta);
     listener.Start ();
 }
开发者ID:tsprates,项目名称:chat-dotnet,代码行数:7,代码来源:ChatServidor.cs

示例9: ModbusTcpSlave_ConnectionClosesGracefully

        public void ModbusTcpSlave_ConnectionClosesGracefully()
        {
            TcpListener slaveListener = new TcpListener(ModbusMasterFixture.TcpHost, ModbusMasterFixture.Port);
            slaveListener.Start();
            ModbusTcpSlave slave = ModbusTcpSlave.CreateTcp(ModbusMasterFixture.SlaveAddress, slaveListener);
            Thread slaveThread = new Thread(slave.Listen);
            slaveThread.IsBackground = true;
            slaveThread.Start();

            using (TcpClient masterClient = new TcpClient(ModbusMasterFixture.TcpHost.ToString(), ModbusMasterFixture.Port))
            {
                ModbusIpMaster master = ModbusIpMaster.CreateIp(masterClient);
                master.Transport.Retries = 0;

                bool[] coils = master.ReadCoils(1, 1);
                Assert.AreEqual(1, coils.Length);

                Assert.AreEqual(1, slave.Masters.Count);
            }

            // give the slave some time to remove the master
            Thread.Sleep(50);

            Assert.AreEqual(0, slave.Masters.Count);

            slaveListener.Stop();
        }
开发者ID:mesta1,项目名称:nmodbus,代码行数:27,代码来源:NModbusTcpSlaveFixture.cs

示例10: BackupProcess

        static void BackupProcess()
        {
            Console.WriteLine("I am backup!");
            
            IPAddress ipAddress = Dns.GetHostEntry("localhost").AddressList[0];
            TcpListener listener = new TcpListener(ipAddress, port);
            listener.Start();
            Socket sock = listener.AcceptSocket();
            Stream str = new NetworkStream(sock);
            StreamReader sr = new StreamReader(str);

            string line = "-1";

            try
            {
                while (true)
                    line = sr.ReadLine();
            }
            catch(IOException)
            { 
                sr.Close();
                listener.Stop();

                PrimaryProcess(Convert.ToInt32(line) + 1);
            }
        }
开发者ID:DanglingPointer,项目名称:TTK4145,代码行数:26,代码来源:Program.cs

示例11: Form2

		public Form2(String hostPort, Form1 form1)
		{
			//
			// Required for Windows Form Designer support
			//
			InitializeComponent();

			//
			// TODO: Add any constructor code after InitializeComponent call
			//
			dataReadyToSend = new AutoResetEvent(false);
			refToForm1 = form1;
			// Resolve the local host.
			IPHostEntry localHost = Dns.Resolve(Dns.GetHostName());
			// Create a local end point for listening.
			IPEndPoint localEndPoint = new IPEndPoint(localHost.AddressList[0], 4001);
			// Instantiate the TCP Listener.
			tcpListener = new TcpListener(localEndPoint);
			tcpListener.Start();
			tcp = tcpListener.AcceptTcpClient();
			ethernetThreadStart = new ThreadStart(this.ThreadProcPollOnEthernet);
			pollDevicesEthernetThread = new Thread(ethernetThreadStart);
			pollDevicesEthernetThread.Name = "Listener's Receive Thread";
			pollDevicesEthernetThread.ApartmentState = System.Threading.ApartmentState.MTA;
			pollDevicesEthernetThread.Start();
		}
开发者ID:spzenk,项目名称:sfdocsamples,代码行数:26,代码来源:Form2.cs

示例12: AcceptClientsAsync

        public static async Task AcceptClientsAsync(TcpListener listener, CancellationToken cancel)
        {
            await Task.Yield();

            while (!cancel.IsCancellationRequested)
            {
                try
                {
                    var timeoutTask = Task.Delay(2000);
                    var acceptTask = listener.AcceptTcpClientAsync();

                    await Task.WhenAny(timeoutTask, acceptTask);
                    if (!acceptTask.IsCompleted)
                        continue;

                    var client = await acceptTask;
                    HandleClientAsync(client, cancel);
                }
                catch (Exception aex)
                {
                    var ex = aex.GetBaseException();
                    Console.WriteLine("Accepting error: " + ex.Message);
                }
            }
        }
开发者ID:vtortola,项目名称:AynchronousTCPListener,代码行数:25,代码来源:Program.cs

示例13: TcpServer

        public TcpServer(IPAddress ip, ushort port)
        {
            if (ip == null)
                throw new NullReferenceException("ip is null");

            _listener = new TcpListener(ip, port);
        }
开发者ID:KingCrazy,项目名称:S115,代码行数:7,代码来源:TCPServer.cs

示例14: FindFreePort

        public int FindFreePort(int startingPort)
        {
            Exception lastException = null;

            for (int i = startingPort; i < 65535; i++)
            {
                try
                {
                    var listener = new TcpListener(IPAddress.Loopback, i);
                    listener.Start();
                    listener.Stop();

                    logger.Debug("Found free port: {0}", i);
                    return i;
                }
                catch (SocketException e)
                {
                    if (e.SocketErrorCode == SocketError.AddressAlreadyInUse)
                        lastException = e;
                    else
                        throw;
                }
            }

            throw lastException;
        }
开发者ID:johnhk,项目名称:SyncTrayzor,代码行数:26,代码来源:FreePortFinder.cs

示例15: HtmlGetServer

        public HtmlGetServer(int Port, TcpListener listener)
        {
            Listener = listener;
            if (Listener==null)
                Listener = new TcpListener(IPAddress.Any, Port);
            Listener.Start();

            while (true)
            {
               try
               {
                    ThreadPool.QueueUserWorkItem(new WaitCallback(ClientThread), Listener.AcceptTcpClient());
                }
               catch { }
                // Принимаем новых клиентов. После того, как клиент был принят, он передается в новый поток (ClientThread)
                // с использованием пула потоков.

                /*
                // Принимаем нового клиента
                TcpClient Client = Listener.AcceptTcpClient();
                // Создаем поток
                Thread Thread = new Thread(new ParameterizedThreadStart(ClientThread));
                // И запускаем этот поток, передавая ему принятого клиента
                Thread.Start(Client);
                */
            }
        }
开发者ID:skorpioniche,项目名称:MultiplayerSnake,代码行数:27,代码来源:HtmlGetServer.cs


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