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


C# Socket.Poll方法代码示例

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


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

示例1: IsConnected

        protected static bool IsConnected(Socket socket)
        {
            if (socket == null)
                return false;

            try
            {
                if (!socket.Poll(1, SelectMode.SelectRead) || socket.Available != 0)
                    return true;
                socket.Close();
                return false;
            }
            catch
            {
                socket.Close();
                return false;
            }
        }
开发者ID:ApInvent,项目名称:SyncPaintBoard,代码行数:18,代码来源:TransportBase.cs

示例2: StartListening

        private void StartListening()
        {
            Socket serverSocket = null;
            EndPoint endPoint = new IPEndPoint(IPAddress.Any, port);
            try
            {
                serverSocket = new Socket(endPoint.AddressFamily, SocketType.Stream, ProtocolType.Tcp);
                serverSocket.Blocking = true;
                serverSocket.Bind(endPoint);
                serverSocket.Listen(queueSize);

                log.Info("server started, listening on port " + port);

                running = true;
                stopped = false;

                while (running)
                {
                    // Calling socket.Accept blocks the thread until the next incoming connection,
                    // making difficult to stop the server from another thread.
                    // The Poll always returns after the specified delay elapsed, or immediately
                    // returns if it detects an incoming connection. It's the perfect method
                    // to make this loop regularly check the running var, ending gracefully 
                    // if requested.
                    if (serverSocket.Poll(SocketPollMicroseconds, SelectMode.SelectRead))
                    {
                        Socket clientSocket = serverSocket.Accept();
                        Interlocked.Increment(ref connectionsCounter.value);
                        ConversionRequest connection = new ConversionRequest(clientSocket, converter, connectionsCounter);
                        // Creating a single thread for every connection has huge costs,
                        // so I leverage the .NET internal thread pool
                        ThreadPool.QueueUserWorkItem(connection.Run);
                    }
                }
            }
            catch (Exception e)
            {
                log.Error("exception", e);
            }
            finally
            {
                if (serverSocket != null) serverSocket.Close();
                running = false;
                stopped = true;
                log.Info("server stopped ("+ connectionsCounter.value + " connections still open)");
            }
        }
开发者ID:matecat,项目名称:MateCat-Win-Converter,代码行数:47,代码来源:ConversionServer.cs

示例3: StartListening

        private void StartListening()
        {
            Socket serverSocket = null;
            EndPoint endPoint = new IPEndPoint(IPAddress.Any, port);
            try
            {
                serverSocket = new Socket(endPoint.AddressFamily, SocketType.Stream, ProtocolType.Tcp);
                serverSocket.Blocking = true;
                serverSocket.Bind(endPoint);
                serverSocket.Listen(queueSize);

                log.Info("server started, listening on port " + port);

                running = true;
                stopped = false;

                while (running)
                {
                    // Calling socket.Accept blocks the thread until the next incoming connection,
                    // making difficult to stop the server from another thread.
                    // The Poll always returns after the specified delay elapsed, or immeidately
                    // returns if it detects an incoming connection. It's the perfect method
                    // to make this loop regularly che the running var, ending gracefully 
                    // if requested.
                    if (serverSocket.Poll(SocketPollMicroseconds, SelectMode.SelectRead))
                    {
                        Socket clientSocket = serverSocket.Accept();
                        log.Info("new request received");
                        ConversionRequest connection = new ConversionRequest(clientSocket, converter);
                        Thread clientThread = new Thread(new ThreadStart(connection.Run));
                        clientThread.Start();
                    }
                }
            }
            catch (Exception e)
            {
                log.Error("exception", e);
            }
            finally
            {
                if (serverSocket != null) serverSocket.Close();
                running = false;
                stopped = true;
                log.Info("server stopped");
            }
        }
开发者ID:sbxlmdsl,项目名称:MateCat-Win-Converter,代码行数:46,代码来源:ConversionServer.cs

示例4: worker

 private void worker()
 {
     Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
     IPEndPoint ipEndPoint = new IPEndPoint(IPAddress.Any, ipPort);
     EndPoint remoteEndPoint = (EndPoint)ipEndPoint;
     socket.Bind(ipEndPoint);
     socket.SetSocketOption(SocketOptionLevel.IP, SocketOptionName.AddMembership, new MulticastOption(IPAddress.Parse(ipAddress)));
     byte[] receivedData = new byte[1024];
     while (_KeepWorking)
     {
         if (socket.Poll(200000, SelectMode.SelectRead))
         {
             socket.Receive(receivedData);
             switch (apiVersionStr)
             {
                 case "0.8":
                     apiVersionInt = 8;
                     parser_v08(receivedData);
                     break;
                 case "1.0+":
                     parser_v10p(receivedData);
                     break;
             }
             receivedData = new byte[1024];
         }
     }
     socket.Close();
 }
开发者ID:KeiserCorp,项目名称:Keiser.M3i.ReceiverDebug,代码行数:28,代码来源:Receiver.cs

示例5: Read

		/// <summary>
		/// Reads an IcmpPacket from the wire using the specified socket from the specified end point
		/// </summary>
		/// <param name="socket">The socket to read</param>
		/// <param name="packet">The packet read</param>
		/// <param name="ep">The end point read from</param>
		/// <returns></returns>
		public virtual bool Read(Socket socket, EndPoint ep, int timeout, out IcmpPacket packet, out int bytesReceived)
		{
			const int MAX_PATH = 256;
			packet = null;
			bytesReceived = 0;

			/*
			 * check the parameters
			 * */

			if (socket == null)
				throw new ArgumentNullException("socket");
			
			if (socket == null)
				throw new ArgumentNullException("ep");		
						
			// see if any data is readable on the socket
			bool success = socket.Poll(timeout * 1000, SelectMode.SelectRead);

			// if there is data waiting to be read
			if (success)
			{
				// prepare to receive data
				byte[] bytes = new byte[MAX_PATH];
				
				bytesReceived = socket.ReceiveFrom(bytes, bytes.Length, SocketFlags.None, ref ep);

				/*
				 * convert the bytes to an icmp packet
				 * */
//				packet = IcmpPacket.FromBytes(bytes);
			}						

			return success;
		}
开发者ID:FireBall1725,项目名称:Carbon.Framework,代码行数:42,代码来源:IcmpPacketReader.cs

示例6: ProcessRequest

 public void ProcessRequest(Socket socket)
 {
     using (socket)
     {
         var requestHandler = _requestHandlerFactory.Create(socket);
         if (socket.Poll(5000000, SelectMode.SelectRead))
         {
             try
             {
                 requestHandler.ProcessRequest();
             }
             catch (Exception e) // Catch all unhandled internal server exceptions
             {
                 if (_serverContext.ExceptionHandler != null)
                 {
                     _serverContext.ExceptionHandler.HandleException(e);
                 }
                 else
                 {
                     Debug.Print("Unhandled exception in web server, Message: " + e.Message + ", StackTrace:  " + e.StackTrace);
                 }
             }
         }
     }
 }
开发者ID:JakeLardinois,项目名称:ScaleIndicatorPrinter,代码行数:25,代码来源:SocketListener.cs

示例7: ExecuteRequest

        public virtual BrowserResponse ExecuteRequest(string url, string method)
        {
            Socket sock = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            sock.Connect(new IPEndPoint(FastCgiServer, FastCgiServerPort));

            // Our request
            ushort requestId = 1;
            Request = new WebServerSocketRequest(sock, requestId);
            Request.SendBeginRequest(Role.Responder, true);
            SendParams(new Uri(url), method);
            Request.SendEmptyStdin();

            // Receive the data from the other side
            if (!sock.Poll(MaxPollTime, SelectMode.SelectRead))
                throw new Exception("Data took too long");

            byte[] buf = new byte[4096];
            int bytesRead;
            bool endRequest = false;
            while ((bytesRead = sock.Receive(buf)) > 0)
            {
                endRequest = Request.FeedBytes(buf, 0, bytesRead).Any(x => x.RecordType == RecordType.FCGIEndRequest);
            }
            if (!endRequest)
                throw new Exception("EndRequest was not received.");

            return new BrowserResponse(Request.AppStatus, Request.Stdout);
        }
开发者ID:james-andrewsmith,项目名称:Fos,代码行数:28,代码来源:Browser.cs

示例8: BroadcastPing

        private static FoundServerInformation BroadcastPing(IPAddress broadcastAddress, int port) {
            using (var socket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp) {
                SendTimeout = OptionLanSocketTimeout,
                ReceiveTimeout = OptionLanSocketTimeout,
                Blocking = false
            }) {
                EndPoint remoteEndPoint = new IPEndPoint(IPAddress.Any, 0);
                var buffer = new byte[3];
                try {
                    socket.SendTo(BitConverter.GetBytes(200), SocketFlags.DontRoute, new IPEndPoint(broadcastAddress, port));
                    if (socket.Poll(OptionLanPollTimeout * 1000, SelectMode.SelectRead)) {
                        socket.ReceiveFrom(buffer, ref remoteEndPoint);
                    }
                } catch (SocketException) {
                    return null;
                }

                if (buffer[0] != 200 || buffer[1] + buffer[2] <= 0) {
                    return null;
                }

                var foundServer = remoteEndPoint as IPEndPoint;
                if (foundServer == null) {
                    return null;
                }

                return new FoundServerInformation {
                    Ip = foundServer.Address.ToString(),
                    Port = BitConverter.ToInt16(buffer, 1)
                };
            }
        }
开发者ID:gro-ove,项目名称:actools,代码行数:32,代码来源:KunosApiProvider_Lan.cs

示例9: ConnectToServerWithTimeout

        /// <summary>
        /// This code is used to connect to a TCP socket with timeout option.
        /// </summary>
        /// <param name="endPoint">IP endpoint of remote server</param>
        /// <param name="timeoutMs">Timeout to wait until connect</param>
        /// <returns>Socket object connected to server</returns>
        public static Socket ConnectToServerWithTimeout(EndPoint endPoint, int timeoutMs)
        {
            var socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            try
            {
                socket.Blocking = false;
                socket.Connect(endPoint);
                socket.Blocking = true;
                return socket;
            }
            catch (SocketException socketException)
            {
                if (socketException.ErrorCode != 10035)
                {
                    socket.Close();
                    throw;
                }

                if (!socket.Poll(timeoutMs * 1000, SelectMode.SelectWrite))
                {
                    socket.Close();
                    throw new NGRIDException("The host failed to connect. Timeout occured.");
                }

                socket.Blocking = true;
                return socket;
            }
        }
开发者ID:ashwinrath,项目名称:NGRID,代码行数:34,代码来源:GeneralHelper.cs

示例10: NTPTime

 /// <summary>
 /// Try to update both system and RTC time using the NTP protocol
 /// </summary>
 /// <param name="TimeServer">Time server to use, ex: pool.ntp.org</param>
 /// <param name="GmtOffset">GMT offset in minutes, ex: -240</param>
 /// <returns>Returns true if successful</returns>
 public DateTime NTPTime(string TimeServer, int GmtOffset = 0)
 {
     Socket s = null;
     DateTime resultTime = DateTime.Now;
     try
     {
         EndPoint rep = new IPEndPoint(Dns.GetHostEntry(TimeServer).AddressList[0], 123);
         s = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
         byte[] ntpData = new byte[48];
         Array.Clear(ntpData, 0, 48);
         ntpData[0] = 0x1B; // Set protocol version
         s.SendTo(ntpData, rep); // Send Request
         if (s.Poll(30 * 1000 * 1000, SelectMode.SelectRead)) // Waiting an answer for 30s, if nothing: timeout
         {
             s.ReceiveFrom(ntpData, ref rep); // Receive Time
             byte offsetTransmitTime = 40;
             ulong intpart = 0;
             ulong fractpart = 0;
             for (int i = 0; i <= 3; i++) intpart = (intpart << 8) | ntpData[offsetTransmitTime + i];
             for (int i = 4; i <= 7; i++) fractpart = (fractpart << 8) | ntpData[offsetTransmitTime + i];
             ulong milliseconds = (intpart * 1000 + (fractpart * 1000) / 0x100000000L);
             s.Close();
             resultTime = new DateTime(1900, 1, 1) + TimeSpan.FromTicks((long)milliseconds * TimeSpan.TicksPerMillisecond);
             Utility.SetLocalTime(resultTime.AddMinutes(GmtOffset));
         }
         s.Close();
     }
     catch
     {
         try { s.Close(); }
         catch { }
     }
     return resultTime;
 }
开发者ID:lavinjj,项目名称:DIYBreweryBrewController,代码行数:40,代码来源:NTPTimeService.cs

示例11: Run

        public static void Run()
        {
            //Debug.Print(StringUtil.Format("APP started {0}.", DateTime.Now));

            NetworkInterface[] allNetworkInterfaces = NetworkInterface.GetAllNetworkInterfaces();
            foreach (var networkInterface in allNetworkInterfaces)
            {
                if (networkInterface.NetworkInterfaceType == NetworkInterfaceType.Ethernet)
                {
                    //networkInterface.PhysicalAddress = new byte[] { 0x00, 0xFF, 0xC3, 0x1E, 0x77, 0x01 };
                    //networkInterface.EnableStaticIP("192.168.0.44", "255.255.255.0", "192.168.0.1");

                    networkInterface.EnableDhcp();
                    Thread.Sleep(2000);
                    Debug.Print(networkInterface.NetworkInterfaceType.ToString());
                    Debug.Print(networkInterface.IPAddress);
                }
            }
            

            Debug.Print("Network interface configured.");
           // Debug.Print(StringUtil.Format("IP {0}, NM {1}, GW {2}.", eth.IPAddress, eth.SubnetMask, eth.GatewayAddress));

            var socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            //IPEndPoint relayEndpoint = new IPEndPoint(IPAddress.Parse("78.46.63.147"), 9090);

            IPEndPoint relayEndpoint = new IPEndPoint(IPAddress.Parse("192.168.0.1"), 80);

            try
            {
                socket.Connect(relayEndpoint);
            }
            catch (Exception ex)
            {
                //Debug.Print(StringUtil.Format("Connect error {0}. ST {1}.", ex.Message, ex.StackTrace));
                Debug.Print(ex.Message);
            }


            while (true)
            {
                try
                {
                    if (socket.Poll(100, SelectMode.SelectRead))
                    {
                        Debug.Print("Socket connected.");
                    }
                }
                catch (Exception ex)
                {
                    Debug.Print("Socket not connected.");
                }


                Thread.Sleep(500);
            }

            
        }
开发者ID:adamlin1970,项目名称:NetmfSTM32,代码行数:59,代码来源:Mountaineer.cs

示例12: Connect

        public void Connect()
        {
            const Int32 c_microsecondsPerSecond = 1000000;            
            try
            {                
                Socket sock = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
                string request = string.Empty;
                int timeout = (query.IndexOf("init") > 0) ? pool + 3 : pool - 1;

                if (Program.TEST) request = "POST /receivertest/receiver.aspx HTTP/1.1\n";
                else request = "POST /ReceiverNew/Receiver HTTP/1.1\n";

                request += "Host: " + common.dname + " \n";
                request += "Content-Type: application/x-www-form-urlencoded\n";     // 
                request += "Connection: close\r\n";
                request += "Content-Length: " + this.query.Length + "\r\n\r\n";
                request += this.query;

                sock.Bind(sock.LocalEndPoint);
                sock.Connect(this.endPoint);
                Byte[] bytesToSend = Encoding.UTF8.GetBytes(request);
                sock.Send(bytesToSend, bytesToSend.Length, 0);
                Byte[] buffer = new Byte[1024];
                String reply = String.Empty;
                while (sock.Poll(timeout * c_microsecondsPerSecond, SelectMode.SelectRead))
                {
                    if (sock.Available == 0)
                        break;
                    Array.Clear(buffer, 0, buffer.Length);
                    Int32 bytesRead = sock.Receive(buffer);
                    reply += new String(Encoding.UTF8.GetChars(buffer));
                }
                if (reply != string.Empty)
                {
                    string header = reply.Substring(0, reply.IndexOf("\r\n\r\n"));
                    string response = reply.Substring(reply.IndexOf("\r\n\r\n")).Trim();   // malina

                    ConnectionSuccess(this, new NetSuccessEventArgs() { NetStatus = netStatus.Success, Header = header, Answers = response });
                }
                else
                {
                    ConnectionSuccess(this, new NetSuccessEventArgs() { NetStatus = netStatus.Failure, Answers = string.Empty });
                }

                sock.Close();
            }
            catch (SocketException se)
            {
                DebugPrint(" Connection socket aborted. " + se.ToString());
                ConnectionSuccess(this, new NetSuccessEventArgs() { NetStatus = netStatus.Failure, Answers = string.Empty });
            }
            catch (Exception e)
            {
                DebugPrint("Connect: Connection died. " + e.ToString());
                ConnectionSuccess(this, new NetSuccessEventArgs() { NetStatus = netStatus.Failure, Answers = string.Empty });
            }            
        }
开发者ID:TomasFilingr,项目名称:WineDispenser-BASIC,代码行数:57,代码来源:Http.cs

示例13: SocketConnected

 private static bool SocketConnected(Socket s)
 {
     bool part1 = s.Poll(1000, SelectMode.SelectRead);
     bool part2 = (s.Available == 0);
     if (part1 & part2)
         return false;
     else
         return true;
 }
开发者ID:highlander12rus,项目名称:CloudsRIS,代码行数:9,代码来源:Files.cs

示例14: Initialize

        public void Initialize(Main p)
        {
            Popup pop = new Popup();
            Byte[] buff = new byte[128];
            _out = new Queue<string>();
            _in = new Queue<string>();
            t = new Treatment();

            t.Initialize(p);
            pop.ShowDialog();
            if (pop.isValid())
            {
                try
                {
                    IPAddress[] IPs = Dns.GetHostAddresses(pop.GetIp());

                    s = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
                    s.Connect(IPs[0], pop.GetPort());
                }
                catch (SocketException e)
                {
                    Console.WriteLine("Error on Socket\nWhat: {0}", e.Message);
                    MessageBox.Show(e.Message, "Connection failure", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    Application.Exit();
                    connected = false;
                    return;
                }
                catch (FormatException e)
                {
                    MessageBox.Show(e.Message, "Invalid port.", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    Application.Exit();
                    connected = false;
                    return;
                }

                if (s.Poll(60000000, SelectMode.SelectRead))
                {
                    connected = true;
                    s.Receive(buff);
                }
                else
                {
                    MessageBox.Show("Connection impossible with the server.", "Connection timeout.", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    connected = true;
                    return;
                }
                if (Encoding.UTF8.GetString(buff).CompareTo("BIENVENUE\n") == 0)
                {
                    s.Send(Encoding.UTF8.GetBytes("GRAPHIC\n"));
                }
            }
            else
            {
                connected = false;
            }
        }
开发者ID:fiahil,项目名称:Zappy,代码行数:56,代码来源:Network.cs

示例15: SocketConnected

 private bool SocketConnected(Socket s)
 {
     if (!s.Connected) return false;
     bool part1 = s.Poll(10000, SelectMode.SelectError);
     bool part2 = (s.Available == 0);
     if (part1 && part2)
         return false;
     else
         return true;
 }
开发者ID:ZeDingo,项目名称:Socks5,代码行数:10,代码来源:Client.cs


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