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


C# Socket.Poll方法代码示例

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


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

示例1: GetNTPTime

        /// <summary>
        /// Get time from NTP server
        /// </summary>
        /// <param name="timeServer">Time server to use</param>
        /// <param name="gmtOffset">GMT offset in minutes</param>
        /// <returns>NTP date-time or DateTime.MinValue when an error has occured.</returns>
        public DateTime GetNTPTime(string timeServer, int gmtOffset = 0)
        {
            this.lastErrorMsg = "";
            Socket s = null;
            try
            {
                // init socket
                EndPoint remoteEP = new IPEndPoint(Dns.GetHostEntry(timeServer).AddressList[0], 123);
                s = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);

                // init request
                byte[] ntpData = new byte[48];
                Array.Clear(ntpData, 0, 48);
                ntpData[0] = 0x1B; // set protocol version

                // send request
                s.SendTo(ntpData, remoteEP);

                // wait 30s if no response, timeout
                if (s.Poll(30 * 1000 * 1000, SelectMode.SelectRead))
                {
                    // get response
                    s.ReceiveFrom(ntpData, ref remoteEP);

                    s.Close();

                    // parse time value
                    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);

                    DateTime ntpTime = new DateTime(1900, 1, 1) + TimeSpan.FromTicks((long)milliseconds * TimeSpan.TicksPerMillisecond);

                    return ntpTime.AddMinutes(gmtOffset);
                }
                else
                {
                    // timeout
                    s.Close();
                    this.lastErrorMsg = "Timed out.";
                }
            }
            catch (Exception e)
            {
                try
                {
                    s.Close();
                }
                catch { }
                this.lastErrorMsg = e.Message;
            }

            return DateTime.MinValue;
        }
开发者ID:Gorgok,项目名称:Fishy-Brains,代码行数:63,代码来源:NTPClient.cs

示例2: GetResponse

 private string GetResponse(Socket s, string query) {
     s.Send(new ASCIIEncoding().GetBytes(query));
     if (!s.Poll(10000000, SelectMode.SelectRead)) { // 10 seconds
         ErrorText.text = "Failed to connect to the server.";
         return null;
     }
     byte[] buffer = new byte[2048];
     int received = s.Receive(buffer);
     string response = new ASCIIEncoding().GetString(buffer, 0, received);
     SplitData data = response.GetFirst();
     if (data.CommandType == "Error") {
         ErrorText.text = "Invalid login credentials.";
         return null;
     }
     return data.Values.GetFirst().Values;
 }
开发者ID:BornToGrill,项目名称:Project-Frequency,代码行数:16,代码来源:LoginController.cs

示例3: ReceiveData

    // -------------------------------------------------------------------------
    void ReceiveData()
    {
        IPEndPoint anyIP = new IPEndPoint(IPAddress.Any, multicastPort);
        EndPoint wtf = (EndPoint) anyIP;

        try {

            Socket udpSocket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
            udpSocket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true);
            udpSocket.SetSocketOption(SocketOptionLevel.IP,SocketOptionName.AddMembership,
                new MulticastOption(IPAddress.Parse(multicastIP)));

            udpSocket.Bind(anyIP);

            while (Thread.CurrentThread.IsAlive)
            {
                if (udpSocket.Poll(1, SelectMode.SelectRead)) {

                    dataMutex.WaitOne();

                    byte[] buffer = new byte[1500];
                    int trueSize = udpSocket.ReceiveFrom(buffer, ref wtf);

                    byte[] trimmedBuffer = new byte[trueSize];
                    Array.Copy(buffer, trimmedBuffer, trueSize);
                    dataList.Add(trimmedBuffer);

                    dataMutex.ReleaseMutex();
                }

                Thread.Sleep(10);
            }

        } catch(Exception e) {
            print(e.ToString());
        }
    }
开发者ID:mcgredonps,项目名称:Unity_DIS,代码行数:38,代码来源:UDPThread.cs

示例4: SendRecvPollSync_TcpListener_Socket

        public void SendRecvPollSync_TcpListener_Socket(IPAddress listenAt, bool pollBeforeOperation)
        {
            const int BytesToSend = 123456;
            const int ListenBacklog = 1;
            const int TestTimeout = 30000;

            var listener = new TcpListener(listenAt, 0);
            listener.Start(ListenBacklog);
            try
            {
                int bytesReceived = 0;
                var receivedChecksum = new Fletcher32();
                Task serverTask = Task.Run(async () =>
                {
                    using (Socket remote = await listener.AcceptSocketAsync())
                    {
                        var recvBuffer = new byte[256];
                        while (true)
                        {
                            if (pollBeforeOperation)
                            {
                                Assert.True(remote.Poll(-1, SelectMode.SelectRead), "Read poll before completion should have succeeded");
                            }
                            int received = remote.Receive(recvBuffer, 0, recvBuffer.Length, SocketFlags.None);
                            if (received == 0)
                            {
                                Assert.True(remote.Poll(0, SelectMode.SelectRead), "Read poll after completion should have succeeded");
                                break;
                            }

                            bytesReceived += received;
                            receivedChecksum.Add(recvBuffer, 0, received);
                        }
                    }
                });

                int bytesSent = 0;
                var sentChecksum = new Fletcher32();
                Task clientTask = Task.Run(async () =>
                {
                    var clientEndpoint = (IPEndPoint)listener.LocalEndpoint;

                    using (var client = new Socket(clientEndpoint.AddressFamily, SocketType.Stream, ProtocolType.Tcp))
                    {
                        await client.ConnectAsync(clientEndpoint.Address, clientEndpoint.Port);

                        if (pollBeforeOperation)
                        {
                            Assert.False(client.Poll(TestTimeout, SelectMode.SelectRead), "Expected writer's read poll to fail after timeout");
                        }

                        var random = new Random();
                        var sendBuffer = new byte[512];
                        for (int remaining = BytesToSend, sent = 0; remaining > 0; remaining -= sent)
                        {
                            random.NextBytes(sendBuffer);

                            if (pollBeforeOperation)
                            {
                                Assert.True(client.Poll(-1, SelectMode.SelectWrite), "Write poll should have succeeded");
                            }
                            sent = client.Send(sendBuffer, 0, Math.Min(sendBuffer.Length, remaining), SocketFlags.None);

                            bytesSent += sent;
                            sentChecksum.Add(sendBuffer, 0, sent);
                        }
                    }
                });

                Assert.True(Task.WaitAll(new[] { serverTask, clientTask }, TestTimeout), "Wait timed out");

                Assert.Equal(bytesSent, bytesReceived);
                Assert.Equal(sentChecksum.Sum, receivedChecksum.Sum);
            }
            finally
            {
                listener.Stop();
            }
        }
开发者ID:ChuangYang,项目名称:corefx,代码行数:79,代码来源:SendReceive.cs

示例5: PollError_Single_Timeout

        public void PollError_Single_Timeout()
        {
            using (var receiver = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp))
            {
                receiver.BindToAnonymousPort(IPAddress.Loopback);

                Assert.False(receiver.Poll(SelectTimeout, SelectMode.SelectError));
            }
        }
开发者ID:er0dr1guez,项目名称:corefx,代码行数:9,代码来源:SelectAndPollTests.cs

示例6: PollWrite_Single_Timeout

        public void PollWrite_Single_Timeout()
        {
            using (var listener = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp))
            {
                listener.BindToAnonymousPort(IPAddress.Loopback);
                listener.Listen(1);
                listener.AcceptAsync();

                Assert.False(listener.Poll(SelectTimeout, SelectMode.SelectWrite));
            }
        }
开发者ID:er0dr1guez,项目名称:corefx,代码行数:11,代码来源:SelectAndPollTests.cs

示例7: PollWrite_Single_Success

 public void PollWrite_Single_Success()
 {
     using (var sender = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp))
     {
         Assert.True(sender.Poll(SelectSuccessTimeoutMicroseconds, SelectMode.SelectWrite));
     }
 }
开发者ID:er0dr1guez,项目名称:corefx,代码行数:7,代码来源:SelectAndPollTests.cs

示例8: PollRead_Single_Success

        public void PollRead_Single_Success()
        {
            using (var receiver = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp))
            using (var sender = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp))
            {
                int receiverPort = receiver.BindToAnonymousPort(IPAddress.Loopback);
                var receiverEndpoint = new IPEndPoint(IPAddress.Loopback, receiverPort);

                sender.SendTo(new byte[1], SocketFlags.None, receiverEndpoint);

                Assert.True(receiver.Poll(SelectSuccessTimeoutMicroseconds, SelectMode.SelectRead));
            }
        }
开发者ID:er0dr1guez,项目名称:corefx,代码行数:13,代码来源:SelectAndPollTests.cs

示例9: SocketConnected

 private 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:stefanseibert,项目名称:padawan101,代码行数:9,代码来源:RotationDistributor.cs

示例10: GetResponse

 public string GetResponse(Socket socket, string query) {
     socket.Send(new ASCIIEncoding().GetBytes(query));
     if (!socket.Poll(1000000, SelectMode.SelectRead)) {
         Debug.LogError("Socket did not respond within 1000000 Micro seconds");
         return null;
     }
     byte[] buffer = new byte[4096];
     int received = socket.Receive(buffer);
     return new ASCIIEncoding().GetString(buffer, 0, received);
 }
开发者ID:BornToGrill,项目名称:Project-Frequency,代码行数:10,代码来源:OnlinePlay.cs

示例11: DownloadCertificates

	static X509CertificateCollection DownloadCertificates (string site)
	{
		Uri uri = new Uri (site);
#if NET_2_0
		IPHostEntry host = Dns.GetHostEntry (uri.Host);
#else
		IPHostEntry host = Dns.Resolve (uri.Host);
#endif
		IPAddress ip = host.AddressList [0];
		Socket socket = new Socket (ip.AddressFamily, SocketType.Stream, ProtocolType.Tcp);
		socket.Connect (new IPEndPoint (ip, uri.Port));
		NetworkStream ns = new NetworkStream (socket, false);
		SslClientStream ssl = new SslClientStream (ns, uri.Host, false, Mono.Security.Protocol.Tls.SecurityProtocolType.Default, null);
		ssl.ServerCertValidationDelegate += new CertificateValidationCallback (CertificateValidation);

		try {
			// we don't really want to write to the server (as we don't know
			// the protocol it using) but we must send something to be sure the
			// SSL handshake is done (so we receive the X.509 certificates).
			StreamWriter sw = new StreamWriter (ssl);
			sw.WriteLine (Environment.NewLine);
			sw.Flush ();
			socket.Poll (30000, SelectMode.SelectRead);
		} finally {
			socket.Close ();
		}

		// we need a little reflection magic to get this information
		PropertyInfo pi = typeof (SslStreamBase).GetProperty ("ServerCertificates", BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public);
		if (pi == null) {
			throw new ArgumentException ("Sorry but you need a newer version of Mono.Security.dll to use this feature.");
		}

		return (X509CertificateCollection) pi.GetValue (ssl, null);
	}
开发者ID:mono,项目名称:gert,代码行数:35,代码来源:test.cs


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