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


C# TcpListener.Pending方法代码示例

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


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

示例1: start

    public static void start(int listenPort, System.Action<StreamWriter, string> handleRequest)
    {
        var server = new TcpListener(IPAddress.Parse("127.0.0.1"), listenPort);
        server.Start();
        Debug.Log("Start server");
        while (Working) {
            try {
                Thread.Sleep(0);
                if (!server.Pending())
                    continue;

                using (var client = server.AcceptTcpClient())
                using (var stream = client.GetStream())
                using (var reader = new StreamReader(stream, Encoding.UTF8))
                using (var writer = new StreamWriter(stream, new UTF8Encoding(false)))
                {
                    Debug.Log("Server Connected");
                    while (!reader.EndOfStream) {
                        var line = reader.ReadLine();
                        handleRequest(writer, line);
                    }
                }
            } catch (System.Exception e) {
                Debug.Log("RPCServer exception " + e);
            }
        }
    }
开发者ID:nobnak,项目名称:JsonUnityServer,代码行数:27,代码来源:Server.cs

示例2: ThreadedTcpSrvr

    public ThreadedTcpSrvr()
    {
        //public List<Song> musicQueue = new List<Song>();
        monocheck();
        client = new TcpListener(8009);
        client.Start();
        Console.WriteLine("Waiting for clients...");
        while (true)
        {
            while (!client.Pending())
            {
                if (musicQueue.Count > 0 && isPlaying == false)
                {
                    isPlaying = true;
                    //we'll play it
                    Song thisSong = musicQueue[0];
                    musicQueue.RemoveAt(0);
                    string currentSong = thisSong.song;
                    // ByteArrayToFile("currentsong.media", currentSong);
                    //Process mplaying = new Process();
                    mplaying.StartInfo.FileName = "mplayer";
                    mplaying.StartInfo.Arguments = currentSong;
                    //mplaying.StartInfo.UseShellExecute = false;
                    mplaying.StartInfo.CreateNoWindow = true;
                    //mplaying.StartInfo.RedirectStandardError = true;
                    //mplaying.StartInfo.RedirectStandardOutput = true;
                    BackgroundWorkerExecProcess(mplaying);
                    System.Console.WriteLine("now playing " + thisSong.info);
                    string previous = Convert.ToString(thisSong.SID - 1);
                    //deleting file is taken care of by the destructor
                    GC.Collect();
                }
                Thread.Sleep(1000);
            }

            ConnectionThread newconnection = new ConnectionThread();
            newconnection.threadListener = this.client;
            Thread newthread = new Thread(new ThreadStart(newconnection.HandleConnection));
            newthread.Start();
            while (newthread.IsAlive)
            {
            }
            byte[] mySong = newconnection.song;
            if (mySong != null)
            {
                int mysongSID = GetSID();
                ByteArrayToFile(SID + ".media", mySong);
                string mySongInfo = GetSongInfo(SID + ".media", SID);
                Song song = new Song(mySongInfo, SID + ".media", mysongSID);
                musicQueue.Add(song);
            }
        }
    }
开发者ID:crowell,项目名称:Linebeck,代码行数:53,代码来源:Program.cs

示例3: listen

    private IEnumerator listen(IPAddress listen_ip, int port)
    {
        TcpListener listener = new TcpListener( listen_ip, port );
        listener.Start();
        while(gameObject.activeSelf){

            if(listener.Pending()){
                TcpClient s = listener.AcceptTcpClient();
                //Debug.Log("got a client! create a HttpProcessor for him and start the process coroutine");
                HttpProcessor processor = new HttpProcessor(s, this);
                StartCoroutine(processor.process());
            }

            yield return wait;
            //yield return new WaitForSeconds(ListenDelay);
        }
    }
开发者ID:simonbroggi,项目名称:UnityWebserver,代码行数:17,代码来源:UnityServer.cs

示例4: runServer

 private void runServer()
 {
     TcpListener myListener = new TcpListener(IPAddress.Parse("192.168.1.199"), PORT);
         myListener.Start();
         callback("开始侦听  端口……" + PORT.ToString());
         while (true)
         {
             if (myListener.Pending())
             {
                 //Socket mySocket = myListener.AcceptSocket();
                 //call = new callDelegate(mySocket.Send);
                 //callback("接收到客户的连接");
                 //Byte[] recvBytes = new Byte[256];
                 //Int32 bytes = mySocket.Receive(recvBytes, recvBytes.Length, SocketFlags.None);
                 //String str = Utils.GetString(recvBytes);
                 //callback("接收:" + str);
                 TcpClient tc = myListener.AcceptTcpClient();
                 call = new callDelegate(tc.Client.Send);
                 Thread th = new Thread(new ParameterizedThreadStart(MyFun));
                 Client cl = new Client(tc, th);
                 Utils.clients.Add(cl);
                 th.Start(cl);
                 callback("客户端连接上来" + tc.Client.RemoteEndPoint);
             }
             else
             {
                 Thread.Sleep(500);
                 //callback("休眠5秒");
             }
         }
 }
开发者ID:phhui,项目名称:SocketServerTest,代码行数:31,代码来源:SocketServer.cs

示例5: main

 public void main()
 {
     listener = new TcpListener(IPAddress.Any, Port);
     listener.Start();
     while (true)
     {
         if (listener.Pending())
         {
             TCPConnection c = new TCPConnection(listener.AcceptTcpClient());
             Console.WriteLine("Connection Added");
             connections.Add(c);
         }
         foreach (TCPConnection c in Connections)
         {
             if (!c.Alive)
             {
                 Console.WriteLine("Connection Lost");
                 c.Kill();
                 connections.Remove(c);
                 break;
             }
             if (c.TimedOut)
             {
                 Console.WriteLine("Connection TimedOut");
                 c.Kill();
                 connections.Remove(c);
                 break;
             }
         }
         Thread.Sleep(20);
     }
 }
开发者ID:Linrstudio,项目名称:projectssynergy,代码行数:32,代码来源:LazyNetworking.cs

示例6: connect

    IEnumerator connect()
    {
        server = new TcpListener(IPAddress.Parse("127.0.0.1"), 13000);
        server.Start();
        logger("server Start ver 1.4.3");
        while (isRunning)
        {
                // check if new connections are pending, if not, be nice and sleep 100ms
            if (!server.Pending())
            {
                Thread.Sleep(100);
            }
            else
            {
                File.Delete("temp.txt");

                TcpClient client = server.AcceptTcpClient();
                logger("connection established");

                NetworkStream ns = client.GetStream();
                const int bufSize = 0x1000;
                byte[] buf = new byte[bufSize];
                bool rep = false;
                Example.CDTIReport report = null;
               // MemoryStream ms = new MemoryStream();
                Thread.Sleep(400);
                long totalBytes = 0;
                int bytesRead = 0;
                while((bytesRead = ns.Read(buf,0,bufSize)) > 0)
                {
                    File.Delete("temp.txt");
                    FileStream file = new FileStream("temp.txt", FileMode.Create);
                    file.Write(buf, 0, bytesRead);
                    logger("temp written");
                   // ms.Write(buf, 0, bytesRead);
                    totalBytes += bytesRead;
                    file.Close();
                    print(bytesRead);

                    FileStream fs = new FileStream("temp.txt", FileMode.Open);
                  /*  try
                    {
                       logger("reading temp");
                        report = Example.CDTIReport.Deserialize(fs);
                        fs.Close();
                        logger("temp read");
                        logger("" +report.Planes.Count);
                        logger("" +report.Ownship);
                        logger("" +report.Timestamp);
                        logger(report.AdvisoryMessage);
                        rep = true;
                        lastReport = report;

                    //}
                   // catch(Exception e)
                    //{
                    //	logger("Exception caught in read" + e.Message); */
                        //fs.Close();
                        //fs = new FileStream("temp.txt", FileMode.Open);
                        try
                        {
                            fs.Seek(4, SeekOrigin.Begin);
                            logger("reading temp");
                            report = CDTIReport.Deserialize(fs);
                            fs.Close();
                            logger("temp read");
                            logger("" + report.Planes.Count);
                            logger("" + report.Ownship);
                            logger("" + report.Timestamp);
                            logger(report.AdvisoryMessage);
                            rep = true;
                            lastReport = report;

                        }
                        catch (Exception f)
                        {
                            logger("Exception caught in read" + f.Message);
                            fs.Close();
                            if(report != null)
                            {
                                lastReport = report;
                                rep = true;
                            }
                        }
                   // }
                    if(rep)
                    {
                        yield return Ninja.JumpToUnity;
                        intake(report);
                        // intake(CDTIReport.Deserialize(ns));
                        yield return Ninja.JumpBack;
                    }
                    rep = false;
                }

                client.Close();
            }
        }

        server.Stop();
//.........这里部分代码省略.........
开发者ID:huner15,项目名称:saas,代码行数:101,代码来源:NetworkInput.cs

示例7: Main

    static void Main() {
        TcpListener server = null;
		CancellationTokenSource cts = new CancellationTokenSource();
		
        //
        // Create a listen socket bind to the server port.
        //

        server = new TcpListener(IPAddress.Parse("127.0.0.1"), SERVER_PORT);

        //
        // Start listening for client requests.
        //

        server.Start();

        //
        // Start the first AcceptTcpClient
        //

        var listenTask = Listen(server, cts.Token);

        //
        // Wait a <enter> from the console to terminate the server. 
        //

        Console.WriteLine("Hit <enter> to exit the server...");
        Console.ReadLine();

        //
        // Before close the listener socket, try to process the connections
        // already accepted by the sockets layer. Since that it is possible
        // that we never see no connections pending, due to an uninterrupted
        // arrival of new connection requests, we poll for a limited amount
        // of time.

        for (int i = 0; i < WAIT_FOR_IDLE_TIME; i += POLLING_INTERVAL) {
            if (!server.Pending())
                break;
            Thread.Sleep(POLLING_INTERVAL);
        }

        //
        // Stop listening.
        //

        server.Stop();

        //
        // Wait until all previously accepted connections are processed.
        // Set the cancellation token as cancelled, and wait until the processing
        // of all accepted connections is finished.
        //

        cts.Cancel();
		try {
			listenTask.Wait();
		} catch (OperationCanceledException) {}

        //
        // Display the number of used IOCP threads.
        //

        Console.WriteLine("--- processed requests: {0}", Volatile.Read(ref requestCount));
    }
开发者ID:Baptista,项目名称:PC,代码行数:65,代码来源:TcpMtEchoServerAsync.cs

示例8: Listen

        private void Listen()
        {
            try
            {
                var listener = new TcpListener(IPAddress.Any, this.ListeningPort);
                listener.Start();
                while (!this.ResetEvent.Wait(100))
                {
                    if (!listener.Pending()) continue;

                    TcpClient tc = listener.AcceptTcpClient();
                    Thread t = new Thread(new ParameterizedThreadStart(this.HandleClient));
                    t.Start(new ClientDescriptor(tc));
                }
            }
            catch { }
            finally
            {
                this.IsRunning = false;
            }
        }
开发者ID:KyLuaa,项目名称:bot,代码行数:21,代码来源:NavServer.cs

示例9: Main


//.........这里部分代码省略.........
		
		onAcceptCallback = delegate(IAsyncResult ar) {
		
			Console.WriteLine("-->OnAcceptCallback(#{0})", Thread.CurrentThread.ManagedThreadId);
		
			//
			// Register the current IOCP thread.
			//
			
			RegisterIocpThread();
			
			/*
			int wrk, iocp;
			ThreadPool.GetAvailableThreads(out wrk, out iocp);
			Console.WriteLine("-->thread #{0}[available: {1}/{2}]",
							  Thread.CurrentThread.ManagedThreadId, wrk, iocp);
			*/
#if BOUND_NESTED_IO_CALLBACKS
		
			if (!ar.CompletedSynchronously) {
				onAcceptProcessing(ar);
			} else {
			
				Console.WriteLine("\n\n\n****COMPLETED SYNCHRONOUSLY ***\n\n");
				
				if (nestedIOCallbacks >= MAX_NESTED_IO_CALLBACKS) {
			
					//
					// If the maximum number of nested callbacks was reached,
					// break the nesting, using a worker thread pool thread.
					//

					ThreadPool.QueueUserWorkItem((_ar) => onAcceptProcessing((IAsyncResult)_ar), ar);
				} else {
					nestedIOCallbacks++;
					onAcceptProcessing(ar);
					nestedIOCallbacks--;
				}
			}
#else

			onAcceptProcessing(ar);

#endif

			Console.WriteLine("<--OnAcceptCallback(#{0})", Thread.CurrentThread.ManagedThreadId);
		};
				
		//
		// Issue the first BeginAcceptTcpClient();
		//
		
		server.BeginAcceptTcpClient(onAcceptCallback, null);
			
		//
		// Wait a <enter> from the console to terminate the server. 
		//
			
		Console.WriteLine("Hit <enter> to exit the server...");
		Console.ReadLine();

		//
		// Before close the listener socket, try to process the connections
		// already accepted by the sockets layer. Since that it is possible
		// that we never see no connections pending, due to an uninterrupted
		// arrival of new connection requests, we poll for a limited amount
		// of time.
			
		for (int i = 0; i < WAIT_FOR_IDLE_TIME; i += POLLING_INTERVAL) {
			if (!server.Pending()) {
				break;
			}
			Thread.Sleep(POLLING_INTERVAL);
		}
		
		//
		// Stop listening.
		//

		server.Stop();
		
		//
		// Wait until all previously accepted connections are processed.
		// Set shutdown in progress, and wait until the processing of all
		// accepted connections is finished.
		//
		
		shutdownInProgress = true;
		Thread.MemoryBarrier();			// Prevent release/acquire hazard!
		if (activeConnections > 0) {
			serverIdle.Wait();
		}

		//
		// Display the number of used IOCP threads.
		//
		
		Thread.Sleep(500);
		ShowUsedIocpThreads();
	}
开发者ID:Baptista,项目名称:PC,代码行数:101,代码来源:TcpMtEchoServer.cs


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