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


C# TcpListener.Start方法代码示例

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


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

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

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

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

示例4: ShouldAllowRestart

 public void ShouldAllowRestart()
 {
     var listener = new TcpListener(9995);
     listener.Start();
     listener.Stop();
     listener.Start();
     Assert.AreEqual(ListenerStatus.Listening, listener.Status);
 }
开发者ID:jpalmero9,项目名称:peer2net,代码行数:8,代码来源:ListenerTests.cs

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

示例6: HttpServer

    public HttpServer(int port)
    {
      prefixes.TryAdd(
        "/favicon.ico",
        new StaticHandler(
          new ResourceResponse(HttpCode.Ok, "image/icon", "favicon"))
        );
      prefixes.TryAdd(
        "/static/browse.css",
        new StaticHandler(
          new ResourceResponse(HttpCode.Ok, "text/css", "browse_css"))
        );
      RegisterHandler(new IconHandler());

      listener = new TcpListener(new IPEndPoint(IPAddress.Any, port));
      listener.Server.Ttl = 32;
      listener.Server.UseOnlyOverlappedIO = true;
      listener.Start();

      RealPort = (listener.LocalEndpoint as IPEndPoint).Port;

      NoticeFormat(
        "Running HTTP Server: {0} on port {1}", Signature, RealPort);
      ssdpServer = new SsdpHandler();

      timeouter.Elapsed += TimeouterCallback;
      timeouter.Enabled = true;

      Accept();
    }
开发者ID:itsmevix,项目名称:FTT-DLNA,代码行数:30,代码来源:HTTPServer.cs

示例7: Start

 public void Start()
 {
     _stop = false;
     _listener = new TcpListener(IPAddress.Any, _port);
     _listener.Start();
     _listener.BeginAcceptSocket(OnAcceptSocket, null);
 }
开发者ID:hide1980,项目名称:mdcm,代码行数:7,代码来源:HL7v2Server.cs

示例8: TCPServer

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

示例9: Main

 static void Main(string[] args)
 {
     bool done = false;
     //TcpListener listener = new TcpListener(portNum); //����VS2005 MSDN �˷����Ѿ���ʱ������ʹ��
     // IPEndPoint�� �������ʶΪIP��ַ�Ͷ˿ں�
     TcpListener listener = new TcpListener(new IPEndPoint(IPAddress.Any, portNum));
     listener.Start();
     while (!done)
     {
         Console.Write("Waiting for connection...");
         TcpClient client = listener.AcceptTcpClient();
         Console.WriteLine("Connection accepted.");
         NetworkStream ns = client.GetStream();
         byte[] byteTime = Encoding.ASCII.GetBytes(DateTime.Now.ToString());
         try
         {
             ns.Write(byteTime, 0, byteTime.Length);
             ns.Close();
             client.Close();
         }
         catch (Exception e)
         {
             Console.WriteLine(e.ToString());
         }
     }
     listener.Stop();
 }
开发者ID:svn2github,项目名称:eztx,代码行数:27,代码来源:tcpserver.cs

示例10: TcpListenerLoop

        // http://stackoverflow.com/questions/7690520/c-sharp-networking-tcpclient
        void TcpListenerLoop()
        {
            try
            {
                m_tcpListener = new System.Net.Sockets.TcpListener(IPAddress.Parse(m_privateIP), m_port);  
                m_tcpListener.Start();
                Console.WriteLine($"*TcpListener is listening on port {m_privateIP}:{m_port}.");
                while (true)
                {
                    var tcpListenerCurrentClientTask = m_tcpListener.AcceptTcpClientAsync();
                    var tcpClient = tcpListenerCurrentClientTask.Result;        // Task.Result is blocking. OK.
                    Console.WriteLine($"TcpListenerLoop.NextClientAccepted.");
                    Utils.Logger.Info($"TcpListenerLoop.NextClientAccepted.");
                    if (Utils.MainThreadIsExiting.IsSet)
                        return; // if App is exiting gracefully, don't start new thread

                    m_tcpClientQueue.Add(tcpClient);     // If it is a long processing, e.g. reading the TcpClient, do it in a separate thread. If it is just added to the queue, don't start a new thread
                    //(new Thread((x) => ReadTcpClientStream(x)) { IsBackground = true }).Start(tcpClient);    // read the BinaryReader() and deserialize in separate thread, so not block the TcpListener loop
                }
            }
            catch (Exception e) // Background thread can crash application. A background thread does not keep the managed execution environment running.
            {
                if (Utils.MainThreadIsExiting.IsSet)
                    return; // if App is exiting gracefully, this Exception is not a problem
                Utils.Logger.Error("Not expected Exception. We send email by StrongAssert and rethrow exception, which will crash App. TcpListenerLoop. " + e.Message + " ,InnerException: " + ((e.InnerException != null) ? e.InnerException.Message : ""));
                StrongAssert.Fail(Severity.ThrowException, "Not expected Exception. We send email by StrongAssert and rethrow exception, which will crash App. TcpListenerLoop. VirtualBroker: manual restart is needed.");
                throw;  // if we don't listen to TcpListener any more, there is no point to continue. Crash the App.
            }
        }
开发者ID:gyantal,项目名称:SQLab,代码行数:30,代码来源:ParallelTcpListener.cs

示例11: Run

 /// <summary>
 ///	Server's main loop implementation.
 /// </summary>
 /// <param name="log"> The Logger instance to be used.</param>
 public void Run( Logger log )
 {
     TcpListener srv = null;
     try
     {
         srv = new TcpListener( IPAddress.Loopback, portNumber );
         srv.Start();
         while ( true )
         {
             log.LogMessage( "Listener - Waiting for connection requests." );
             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
              _dispatcher.ProcessConnection(socket.GetStream(), log);
              //Handler protocolHandler = new Handler( socket.GetStream(), log );
                 // Synchronously process requests made through de current TCP connection
                 //Task.Factory.StartNew((handler) => ((Handler) handler).Run(), protocolHandler);
                 //protocolHandler.Run();
             Program.ShowInfo( Store.Instance );
         }
     }
     finally
     {
         log.LogMessage( "Listener - Ending." );
         if ( srv != null )
         {
             srv.Stop();
         }
     }
 }
开发者ID:driverpt,项目名称:PC-1112SI,代码行数:36,代码来源:Listener.cs

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

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

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

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


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