• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    公众号

C# Sockets.TcpListener类代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

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



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


示例16: Start

 public void Start(int port)
 {
     _keepRunning = true;
     _tcpListener = new TcpListener(IPAddress.Any, port);
     _listenThread = new Thread(ListenForConnections);
     _listenThread.Start();
 }
开发者ID:GTuritto,项目名称:BrightstarDB,代码行数:7,代码来源:NodeComms.cs


示例17: Initiate

        public override void Initiate()
        {
            base.Initiate();

            Console.WriteLine("Web communicator");
            Console.Write("Starting socket...");
            try
            {
                server = new TcpListener(IPAddress.Any, portNumber);
                server.Start();
            }
            catch
            {
                Program.Shutdown("Server Startup Failed");
                return;
            }
            Console.WriteLine("Done");

            while (Program.Update)
            {
                TcpClient newClient = server.AcceptTcpClient();

                ThreadPool.QueueUserWorkItem(new WaitCallback(ProcessClient), newClient);
            }
        }
开发者ID:AaronClaydon,项目名称:pocketSteam-archive,代码行数:25,代码来源:WebCommunicator.cs


示例18: ReadLineAsync_ThrowsOnConnectionClose

        public async Task ReadLineAsync_ThrowsOnConnectionClose()
        {
            TcpListener listener = new TcpListener(IPAddress.Loopback, 0);

            try
            {
                listener.Start();
                Task<TcpClient> acceptTask = listener.AcceptTcpClientAsync();

                TcpClient client = new TcpClient();
                await client.ConnectAsync(IPAddress.Loopback, ((IPEndPoint)listener.LocalEndpoint).Port);

                using (TcpClient serverTcpClient = await acceptTask)
                {
                    TcpClientConnectionChannel channel = new TcpClientConnectionChannel(serverTcpClient);
                    client.Dispose();

                    await Assert.ThrowsAsync<ConnectionUnexpectedlyClosedException>(async () =>
                    {
                        await channel.ReadLineAsync();
                    });
                }
            }
            finally
            {
                listener.Stop();
            }
        }
开发者ID:rnwood,项目名称:smtp4dev,代码行数:28,代码来源:TcpClientConnectionChannelTests.cs


示例19: ServerBase

        public ServerBase(string ip, int port)
        {
            var bindIP = IPAddress.None;

            if (!IPAddress.TryParse(ip, out bindIP))
            {
                Log.Normal($"Server can't be started: Invalid IP-Address ({ip})");
                Console.ReadKey(true);

                Environment.Exit(0);
            }

            try
            {
                listener = new TcpListener(bindIP, port);
                listener.Start();

                if (isRunning = listener.Server.IsBound)
                    new Thread(AcceptConnection).Start(200);
            }
            catch (Exception ex)
            {
                ExceptionLog.Write(ex);

                Log.Error(ex.Message);
            }
        }
开发者ID:GlassFace,项目名称:Arctium-WoW,代码行数:27,代码来源:ServerBase.cs


示例20: Server

        /// <summary>
        /// Create an new Instance of the TCP-Listener on Port 5000
        /// </summary>
        internal Server()
        {
            try
            {
                AnrlDB.AnrlDataContext db = new AnrlDB.AnrlDataContext();
                if (!db.DatabaseExists())
                {
                    db.CreateDatabase();
                }

                CalculateTabels = new System.Timers.Timer(20000);
                CalculateTabels.Elapsed += new ElapsedEventHandler(CalculateTabels_Elapsed);
                CalculateTabels.Start();

                running = true;
                this.tcpListener = new TcpListener(IPAddress.Any, 5000);
                this.listenThread = new Thread(new ThreadStart(ListenForClients));
                this.listenThread.Start();
                db.Dispose();
            }
            catch (Exception ex)
            {
                Logger.Log("Exception in Server.Server" + ex.ToString(), 11);
            }
        }
开发者ID:helios57,项目名称:anrl,代码行数:28,代码来源:Reciever.cs



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


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
C# Sockets.UdpClient类代码示例发布时间:2022-05-26
下一篇:
C# Sockets.TcpClient类代码示例发布时间:2022-05-26
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap