Poll() публичный Метод

public Poll ( int microSeconds, SelectMode mode ) : bool
microSeconds int
mode SelectMode
Результат bool
Пример #1
15
        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;
            }
        }
        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");
            }
        }
        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)");
            }
        }
Пример #4
0
        /// <summary>
        /// Send the response data to the client.
        /// </summary>
        private void Sender()
        {
            // If in async mode.
            if (_context != null && _context.IsAsyncMode)
            {
                // Poll the socket when data can be sent.
                if (_socket != null && _socket.Connected)
                {
                    // If read to sent.
                    bool polled = false;

                    try
                    {
                        // Send until empty.
                        while (_responseStream != null && _responseStream.Length > 0)
                        {
                            // If read to sent.
                            polled = _socket.Poll(10, SelectMode.SelectWrite);

                            // If read to send.
                            if (polled)
                            {
                                // Send the data.
                                SocketSend(SendData());
                            }
                        }
                    }
                    catch { }
                }
            }
        }
Пример #5
0
        //
        //
        //
        public int ReceiveBytes()
        {
            Array.Clear(_receiveBuffer, 0, _receiveBuffer.Length);

            if (_socket == null)
            {
                throw new SocketException("Socket is null.");
            }

            _socket.Poll(-1, SNS.SelectMode.SelectRead);                // wait until we can read

            // read the 4 byte header that tells us how many bytes we will get
            byte[] readHeader = new byte[4];
            _socket.Receive(readHeader, 0, 4, SNS.SocketFlags.None);

            int bytesToRead = BitConverter.ToInt32(readHeader, 0);
            //Helper.WriteLine( "+++bytesToRead==" + bytesToRead ) ;

            // read the bytes in a loop
            int readBlockSize = (int)_socket.GetSocketOption(SNS.SocketOptionLevel.Socket, SNS.SocketOptionName.ReceiveBuffer);
            //Helper.WriteLine( "+++readBlockSize==" + readBlockSize ) ;

            int bytesReadSoFar = 0;

            while (true)
            {
                int bytesLeftToRead = bytesToRead - bytesReadSoFar;
                if (bytesLeftToRead <= 0)
                {
                    break;                                          // finished receiving
                }
                _socket.Poll(-1, SNS.SelectMode.SelectRead);        // wait until we can read

                // do the read
                int bytesToReadThisTime = Math.Min(readBlockSize, bytesLeftToRead);

                if (bytesToReadThisTime + bytesReadSoFar > SocketConstants.SOCKET_MAX_TRANSFER_BYTES)
                {
                    throw new SocketException("You are trying to read " + bytesToRead + " bytes. Dont read more than " + SocketConstants.SOCKET_MAX_TRANSFER_BYTES + " bytes.");
                }

                int bytesReadThisTime = _socket.Receive(_receiveBuffer, bytesReadSoFar, bytesToReadThisTime, SNS.SocketFlags.None);
                //Helper.WriteLine( "+++bytesReadThisTime==" + bytesReadThisTime ) ;

                bytesReadSoFar += bytesReadThisTime;
            }

            _statsBytesReceived += bytesReadSoFar;              // update stats

            //Helper.WriteLine( "+++finished reading"  ) ;
            return(bytesReadSoFar);
        }
Пример #6
0
        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)
                };
            }
        }
Пример #7
0
        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);
        }
Пример #8
0
        /// <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;
            }
        }
Пример #9
0
        static void Start()
        {
            var socket = new System.Net.Sockets.Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
            //var ip = new IPAddress(new byte[] { 192, 168, 1, 87 });
            var endPoint = new IPEndPoint(IPAddress.Any, MAPLE_SERVER_BROADCASTPORT);

            socket.Connect(endPoint);

            //byte[] bytesToSend = Encoding.UTF8.GetBytes(msg);

            while (true)
            {
                //socket.SendTo(bytesToSend, bytesToSend.Length, SocketFlags.None, endPoint);
                while (socket.Poll(2000000, SelectMode.SelectRead))
                {
                    if (socket.Available > 0)
                    {
                        byte[]   inBuf       = new byte[socket.Available];
                        EndPoint recEndPoint = new IPEndPoint(IPAddress.Any, 0);
                        socket.ReceiveFrom(inBuf, ref recEndPoint);
                        //if (!recEndPoint.Equals(endPoint))// Check if the received packet is from the 192.168.0.2
                        //    continue;
                        Debug.WriteLine(new String(Encoding.UTF8.GetChars(inBuf)));
                    }
                }
                Thread.Sleep(100);
            }
        }
 /// <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;
 }
 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);
                 }
             }
         }
     }
 }
Пример #12
0
        /// <summary>
        /// Processes the request.
        /// </summary>
        private void ProcessRequest()
        {
            const Int32 c_microsecondsPerSecond = 1000000;

            // 'using' ensures that the client's socket gets closed.
            using (m_clientSocket)
            {
                // Wait for the client request to start to arrive.
                Byte[] buffer = new Byte[1024];
                if (m_clientSocket.Poll(5 * c_microsecondsPerSecond,
                                        SelectMode.SelectRead))
                {
                    // If 0 bytes in buffer, then the connection has been closed,
                    // reset, or terminated.
                    if (m_clientSocket.Available == 0)
                    {
                        return;
                    }

                    // Read the first chunk of the request (we don't actually do
                    // anything with it).
                    Int32 bytesRead = m_clientSocket.Receive(buffer,
                                                             m_clientSocket.Available, SocketFlags.None);

                    // Return a static HTML document to the client.
                    String s =
                        "HTTP/1.1 200 OK\r\nContent-Type: text/html; charset=utf-8\r\n\r\n<html><head><title>.NET Micro Framework Web Server</title></head>" +
                        "<body><bold><a href=\"http://www.microsoft.com/netmf/\">Learn more about the .NET Micro Framework by clicking here</a></bold></body></html>";
                    m_clientSocket.Send(Encoding.UTF8.GetBytes(s));
                }
            }
        }
 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();
 }
		/// <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;
		}
Пример #15
0
        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);
            }

            
        }
Пример #16
0
 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;
 }
Пример #17
0
        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 });
            }            
        }
Пример #18
0
 public static bool IsConnected(this Sockets.Socket Socket)
 {
     try {
         return(!(Socket.Poll(1, Sockets.SelectMode.SelectRead) && Socket.Available == 0));
     }
     catch (Sockets.SocketException) {
         return(false);
     }
 }
Пример #19
0
        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;
            }
        }
Пример #20
0
 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;
 }
Пример #21
0
 bool SocketConnected(Socket s)
 {
     bool part1 = s.Poll(0, SelectMode.SelectRead);
     bool part2 = (s.Available == 0);
     if (part1 & part2)
     {//connection is closed
         return false;
     }
     return true;
 }
Пример #22
0
 /// <summary>
 ///     checks if a socket has data available
 /// </summary>
 /// <param name="socket">Socket</param>
 /// <returns><b>true</b> if data is available; <b>false</b> otherwise</returns>
 internal static bool IsDataAvailable(this System.Net.Sockets.Socket socket)
 {
     try
     {
         if (socket != null && !socket.Poll(0, SelectMode.SelectRead) && !socket.Poll(0, SelectMode.SelectError))
         {
             byte[] buffer = new byte[1];
             if (socket.Receive(buffer, SocketFlags.Peek) != 0)
             {
                 return(true);
             }
         }
     }
     catch
     {
         /* IGNORE */
     }
     return(false);
 }
Пример #23
0
        /// <summary>
        /// Issues a request for the root document on the specified server.
        /// </summary>
        /// <param name="Proxy"></param>
        /// <param name="URL"></param>
        /// <param name="port"></param>
        /// <returns></returns>
        private static String GetWebPage(String Proxy, String URL, Int32 port)
        {
            const Int32 c_microsecondsPerSecond = 1000000;
            string      host   = GetHostFromURL(URL);
            string      server = Proxy.Length > 0 ? Proxy : host;

            // Create a socket connection to the specified server and port.
            using (Socket serverSocket = ConnectSocket(server, port))
            {
                // Send request to the server.
                String request = "GET " + URL + " HTTP/1.1\r\nHost: " + host +
                                 "\r\nConnection: Close\r\n\r\n";
                Byte[] bytesToSend = Encoding.UTF8.GetBytes(request);
                serverSocket.Send(bytesToSend, bytesToSend.Length, 0);

                // Reusable buffer for receiving chunks of the document.
                Byte[] buffer = new Byte[1024];

                // Accumulates the received page as it is built from the buffer.
                String page = String.Empty;

                // Wait up to 30 seconds for initial data to be available.  Throws
                // an exception if the connection is closed with no data sent.
                DateTime timeoutAt = DateTime.Now.AddSeconds(30);
                while (serverSocket.Available == 0 && DateTime.Now < timeoutAt)
                {
                    System.Threading.Thread.Sleep(100);
                }

                // Poll for data until 30-second timeout.  Returns true for data and
                // connection closed.
                while (serverSocket.Poll(30 * c_microsecondsPerSecond,
                                         SelectMode.SelectRead))
                {
                    // If there are 0 bytes in the buffer, then the connection is
                    // closed, or we have timed out.
                    if (serverSocket.Available == 0)
                    {
                        break;
                    }

                    // Zero all bytes in the re-usable buffer.
                    Array.Clear(buffer, 0, buffer.Length);

                    // Read a buffer-sized HTML chunk.
                    Int32 bytesRead = serverSocket.Receive(buffer);

                    // Append the chunk to the string.
                    page = page + new String(Encoding.UTF8.GetChars(buffer));
                }

                // Return the complete string.
                return(page);
            }
        }
Пример #24
0
 public static bool IsConnected(Socket socket)
 {
     try
     {
         return !(socket.Poll(1, SelectMode.SelectRead) && socket.Available == 0);
     }
     catch (SocketException)
     {
         return false;
     }
 }
Пример #25
0
 /// <summary>
 ///     checks if a socket is connected
 /// </summary>
 /// <param name="socket">Socket</param>
 /// <returns><b>true</b> if connected; <b>false</b> otherwise</returns>
 internal static bool IsConnected(this System.Net.Sockets.Socket socket)
 {
     try
     {
         if (socket != null && !socket.Poll(0, SelectMode.SelectRead) && socket.Available == 0)
         {
             return(false);
         }
     }
     catch { }
     return(false);
 }
Пример #26
0
        public void Start()
        {
            if (serverSocket == null)
            {
                serverSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
                IPEndPoint localEP = new IPEndPoint(IPAddress.Any, port);
                serverSocket.Bind(localEP);
                serverSocket.Listen(int.MaxValue);

                isStopped = false;

                new Thread(delegate
                {
                    using (serverSocket)
                    {
                        while (!isStopped)
                        {
                            try
                            {
                                if (serverSocket.Poll(1000 * 10, SelectMode.SelectRead))
                                {
                                    TcpSession session = new TcpSession(serverSocket.Accept());
                                    session.DataReceived += new TcpSessionDataReceivedEventHandler(NetworkClient_DataReceived);
                                    session.Disconnected += new TcpSessionEventHandler(NetworkClient_Disconnected);
                                    sessions.Add(session);

                                    if (SessionConnected != null)
                                        SessionConnected(session);

                                    session.Start();
                                }
                            }
                            catch (SocketException e)
                            {
                                if (e.ErrorCode != 10035)
                                    break;
                            }
                            catch (Exception e)
                            {
                                Debug.Print(e.Message);
                                break;
                            }
                            Thread.Sleep(0);
                        }
                    }

                    serverSocket.Close();
                    serverSocket = null;
                    sessions.Clear();
                }).Start();
            }
        }
Пример #27
0
        public static bool CanWrite(Socket socket)
        {
            if (socket.Connected)
            {
#if FEATURE_SOCKET_POLL
                return socket.Poll(-1, SelectMode.SelectWrite);
#else
                return true;
#endif // FEATURE_SOCKET_POLL
            }

            return false;
        }
Пример #28
0
        /// <summary>
        /// 是否连接了
        /// </summary>
        /// <param name="socket"></param>
        /// <returns></returns>
        public static bool IsSocketConnected(this System.Net.Sockets.Socket socket)
        {
            bool part1 = socket.Poll(1000, SelectMode.SelectRead);
            bool part2 = (socket.Available == 0);

            if (part1 && part2)
            {
                return(false);
            }
            else
            {
                return(true);
            }
        }
Пример #29
0
        public static bool CanRead(Socket socket)
        {
            if (socket.Connected)
            {
#if FEATURE_SOCKET_POLL
                return socket.Poll(-1, SelectMode.SelectRead) && socket.Available > 0;
#else
                return true;
#endif // FEATURE_SOCKET_POLL
            }

            return false;

        }
Пример #30
0
        bool SocketConnected(System.Net.Sockets.Socket s)
        {
            bool part1 = s.Poll(1000, SelectMode.SelectRead);
            bool part2 = (s.Available == 0);

            if (part1 && part2)
            {
                return(false);
            }
            else
            {
                return(true);
            }
        }
Пример #31
0
        public static void Main()
        {
            uint watchdogTimer = 1000;

            PWM umbrella = new PWM(Pins.GPIO_PIN_D10); //Right controller

            Socket receiveSocket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
            receiveSocket.Bind(new IPEndPoint(IPAddress.Any, 4444));
            byte[] rxData = new byte[10]; // Incoming data buffer
            double raw_speed = 0;

            while (true) /* Main program loop */
            {
                /* Try to receive new data - spend 100uS waiting */
                if (receiveSocket.Poll(100, SelectMode.SelectRead))
                {
                    int rxCount = receiveSocket.Receive(rxData);
                    watchdogTimer = 0;
                }

                if (watchdogTimer < 200)   // Only enable the robot if data was received recently
                {
                    // 900 (full rev) to 2100 (full fwd), 1500 is neutral

                    raw_speed += (rxData[0] - 127.5) * .001; // Add the value of the stick to the current speed
                    // Mediate added speed to negative if it's below center line(on ipgamepad). Make the added speed very little because the mount of UDP packets is large.
                    // map function only accept input between 0-255
                    if (raw_speed < 0)
                    {
                        raw_speed = 0;
                    }
                    else if (raw_speed > 255)
                    {
                        raw_speed = 255;
                    }
                    // Stick maintains speed unless calibrate changes.
                    umbrella.SetPulse(20000, map((uint)raw_speed, 0, 255, 1500, 2100)); // Right controller 1500-2100 -- only positive

                    watchdogTimer++;
                }
                else
                {
                    // Disable the robot
                    umbrella.SetDutyCycle(0);
                }
            }
        }
            private void ProcessRequest()
            {
                const int c_microsecondsPerSecond = 1000000;

                using (clientSocket)
                {
                    while (true)
                    {
                        try
                        {
                            if (clientSocket.Poll(5 * c_microsecondsPerSecond, SelectMode.SelectRead))
                            {
                                // If the butter is zero-lenght, the connection has been closed or terminated.
                                if (clientSocket.Available == 0)
                                {
                                    break;
                                }

                                byte[] buffer    = new byte[clientSocket.Available];
                                int    bytesRead = clientSocket.Receive(buffer, clientSocket.Available, SocketFlags.None);

                                byte[] data = new byte[bytesRead];
                                buffer.CopyTo(data, 0);

                                DataReceivedEventArgs args = new DataReceivedEventArgs(clientSocket.LocalEndPoint, clientSocket.RemoteEndPoint, data);
                                socket.OnDataReceived(args);

                                if (args.ResponseData != null)
                                {
                                    clientSocket.Send(args.ResponseData);
                                }

                                if (args.Close)
                                {
                                    break;
                                }
                            }
                        }
                        catch (Exception)
                        {
                            break;
                        }
                    }
                }
            }
Пример #33
0
 public static void Main()
 {
     using (Socket serverSocket = new Socket(AddressFamily.InterNetwork,
                                             SocketType.Dgram,
                                             ProtocolType.Udp))
     {
         EndPoint remoteEndPoint = new IPEndPoint(IPAddress.Any, port);
         serverSocket.Bind(remoteEndPoint);
         if (serverSocket.Poll(-1, //timeout in micro seconds
                                    SelectMode.SelectRead))
         {
             byte[] inBuffer = new byte[serverSocket.Available];
             int count = serverSocket.ReceiveFrom(inBuffer, ref remoteEndPoint);
             string message = new string(Encoding.UTF8.GetChars(inBuffer));
             Debug.Print("Received '" + message + "'.");
         }
     }
 }
Пример #34
0
        /// <summary>
        /// polls socket if endpoint is available
        /// <seealso cref="System.Net.Sockets.Socket"/>
        /// </summary>
        /// <param name="s">socket to check</param>
        /// <returns></returns>
        private bool IsSocketConnected(System.Net.Sockets.Socket s)
        {
            if (s == null)
            {
                return(false);
            }
            bool poll  = s.Poll(1000, System.Net.Sockets.SelectMode.SelectRead);
            bool avail = (s.Available == 0);

            if (poll && avail)
            {
                return(false);
            }
            else
            {
                return(true);
            }
        }
Пример #35
0
        //check connection
        public static bool CheckConnection(Socket socket)
        {
            if (socket == null)
                return false;

            try
            {
                //if the socket says connected we test it to check if its true or not
                //if it says not connected then its clearly not connected
                if (socket.Connected)
                {
                    //poll the connection. the poll will return true if :
                    // - a connection is pending
                    // - data is available for reading
                    // - connection is closed or unavailable
                    //
                    // so if it returns false, the connection is there but nothing can be read
                    // if its true, we need to check if we can read data. if we can't, its either pending (useless) or closed (even more useless)
                    // so we mark it as closed.
                    bool bpoll = false;
                    bpoll = socket.Poll(0, SelectMode.SelectRead);
                    if (bpoll)
                    {
                        byte[] buff = new byte[1];
                        int recv_value = socket.Receive(buff, SocketFlags.Peek);
                        if (recv_value <= 0)
                        {
                            // Client disconnected
                            return false;
                        }
                    }
                }
                else
                    return false;

            }
            catch
            {
                //something went wrong. im guessing connection is closed but meh. lets just assume connection is a no go
                return false;
            }
            return true;
        }
Пример #36
0
        // Methods ============================================================================
        public override void Start(IPEndPoint ep)
        {
            // Verify IPEndPoints
            IPEndPoint[] globalEPs = IPGlobalProperties.GetIPGlobalProperties().GetActiveUdpListeners();
            foreach (IPEndPoint globalEP in globalEPs) {
                if (ep.Equals(globalEP))
                    throw new ApplicationException(ep.ToString() + " is in listening.");
            }

            System.Threading.Thread thread = new System.Threading.Thread(() =>
            {
                server = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
                server.Bind(ep);

                /// ** Report ListenerStarted event
                if (ListenStarted != null)
                    ListenStarted(this, new ListenEventArgs(ep));

                EndPoint epClient = new IPEndPoint(IPAddress.Any, 0);
                isExitThread = false;
                while (true) {
                    if (server.Poll(500000, SelectMode.SelectRead)) {
                        int bytesRead = server.ReceiveFrom(readbuffer, readbuffer.Length, SocketFlags.None, ref epClient);

                        /// ** Report ClientReadMsg event
                        if (ClientRecvPack != null)
                            ClientRecvPack(this, new ClientEventArgs(ep, epClient, readbuffer.Take(bytesRead).ToArray()));
                    } else if (isExitThread == true) {
                        isExitThread = false;
                        break;
                    }
                }

                server.Close();

                /// ** Report ListenerStopped event
                if (ListenStopped != null)
                    ListenStopped(this, new ListenEventArgs(ep));
            });

            thread.IsBackground = true;
            thread.Start();
        }
Пример #37
0
        public static bool IsSocketConnected_Poll(System.Net.Sockets.Socket socket)
        {
            #region remarks

            /* As zendar wrote, it is nice to use the Socket.Poll and Socket.Available, but you need to take into conside                ration
             * that the socket might not have been initialized in the first place.
             * This is the last (I believe) piece of information and it is supplied by the Socket.Connected property.
             * The revised version of the method would looks something like this:
             * from:http://stackoverflow.com/questions/2661764/how-to-check-if-a-socket-is-connected-disconnected-in-c */
            #endregion

            #region 过程
            if (socket == null)
            {
                return(false);
            }
            return(!((socket.Poll(1000, SelectMode.SelectRead) && (socket.Available == 0)) || !socket.Connected));

            #endregion
        }
 internal void SendInternalServerError(Socket socket, System.Exception e)
 {
     var response = "Internal server error\r\n\r\nException\r\nMessage:\r\n" + e.Message + "\r\nStack Trace:\r\n" + e.StackTrace;
     var length = response.Length;
     string innerException = string.Empty;
     if (e.InnerException != null)
     {
         innerException = "\r\nInner Exception: \r\nMessage: " + e.InnerException.Message + "\r\nStack Trace: " + e.InnerException.StackTrace;
         length += innerException.Length;
     }
     var header = "HTTP/1.1 500 Internal Server Error\r\nContent-Length: " + length + "\r\nConnection: close\r\n\r\n";
     if (socket.Poll(5000000, SelectMode.SelectWrite))
     {
         socket.Send(Encoding.UTF8.GetBytes(header), header.Length, SocketFlags.None);
         socket.Send(Encoding.UTF8.GetBytes(response), response.Length, SocketFlags.None);
         if (innerException != string.Empty)
         {
             socket.Send(Encoding.UTF8.GetBytes(innerException), innerException.Length, SocketFlags.None);
         }
     }
 }
        //* Runs as a background task to reconnect if connection is lost
        private void TestConnection(object cancelToken)
        {
            System.Threading.CancellationToken token = (System.Threading.CancellationToken)cancelToken;

            while (!token.IsCancellationRequested)
            {
                //Console.WriteLine("Top of While")
                if (AutoConnect)
                {
                    if (WorkSocket != null)
                    {
                        if ((WorkSocket.Poll(2000, SelectMode.SelectRead)) && (WorkSocket.Available == 0))
                        {
                            try
                            {
                                CloseConnection();
                                Connect();
                            }
                            catch (Exception ex)
                            {
                            }
                            //Console.WriteLine(Now & "Open again")
                        }
                    }
                    else
                    {
                        try
                        {
                            Connect();
                        }
                        catch (Exception ex)
                        {
                        }
                    }
                }

                token.WaitHandle.WaitOne(3000);
                //Threading.Thread.SpinWait(2000)
            }
        }
Пример #40
0
        private Socket tryGetSocket()
        {
            Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            //            socket.Blocking = false;

            byte[] byteAddress = new byte[] { 127, 0, 0, 1 };
            IPAddress ipAddress = new IPAddress(byteAddress);
            try
            {
                socket.Connect(ipAddress, port);
            }
            catch (SocketException socketException)
            {
                if (socketException.ErrorCode == 10035)
                { // WSAEWOULDBLOCK
                    bool socketGood = socket.Poll(10000000, SelectMode.SelectWrite);
                    if (!socketGood) return null;
                }
            }

            return socket;
        }
Пример #41
0
        public static bool TestSocketConnection(IPEndPoint endPoint, int port, int timeoutMs)
        {
            Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);

            try
            {
                // do not block - do not want to be forced to wait on (too- long) timeout
                socket.Blocking = false;

                // initiate connection - will cause exception because we're not  blocking
                socket.Connect(endPoint);
                return false;
            }
            catch (SocketException socketException)
            {
                // check if this exception is for the expected 'Would Block' error
                if (socketException.ErrorCode != 10035)
                {
                    socket.Close();
                    // the error is not 'Would Block', so propogate the exception
                    return false;
                }
                // if we get here, the error is 'Would Block' so just continue  execution   }
                // wait until connected or we timeout
                int timeoutMicroseconds = timeoutMs * 1000;
                if (socket.Poll(timeoutMicroseconds, SelectMode.SelectRead) == false)
                {
                    // timed out
                    socket.Close();
                    return false;
                }

                // *** AT THIS POINT socket.Connected SHOULD EQUAL TRUE BUT  IS FALSE!  ARGH!
                // set socket back to blocking
                socket.Blocking = true;
                socket.Close();
                return true;
            }
        }
Пример #42
0
        /// <summary>
        /// This function checks polls a socket to see if it's connected
        /// </summary>
        /// <param name="target">The Socket to check</param>
        /// <returns>True if connected; otherwise, false</returns>
        private bool IsSocketConnected(System.Net.Sockets.Socket target)
        {
            if (!target.Connected)
            {
                return(false);
            }
            try
            {
                bool bstate = target.Poll(1, System.Net.Sockets.SelectMode.SelectRead);
                if (bstate & (target.Available == 0))
                {
                    return(false);
                }

                return(true);
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.ToString());
                return(false);
            }
        }
Пример #43
0
        /// <summary>
        /// Initializes a new instance of the <see cref="RestClient"/> class
        /// </summary>
        /// <param name="host">
        /// The REST API host name
        /// </param>
        /// <param name="port">
        /// The port on which to connect to the REST API
        /// </param>
        public RestClient(string host, int port)
        {
            Host = host;

            var hostEntry = Dns.GetHostEntry(host);
            foreach (var address in hostEntry.AddressList)
            {
                if (address == null)
                {
                    continue;
                }

                var ipEndPoint = new IPEndPoint(address, port);

                var socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
                try
                {
                    socket.Connect(ipEndPoint);
                    var isConnected = socket.Poll(10, SelectMode.SelectWrite);

                    if (isConnected)
                    {
                        IpEndPoint = ipEndPoint;
                        break;
                    }
                }
                catch (Exception e)
                {
                    #if DEBUG
                    Console.WriteLine("Error connecting to host: " + e.Message);
                    #endif
                }
                finally
                {
                    socket.Close();
                }
            }
        }
Пример #44
0
 /// <summary>
 ///  Determine whether data is ready to be read
 /// </summary>
 public static bool IsDataAvailable(this System.Net.Sockets.Socket s)
 {
     return(s.Poll(1000, SelectMode.SelectRead) && (s.Available > 0));
 }
Пример #45
0
 bool Utils.Wrappers.Interfaces.ISocket.Poll(int microSeconds, System.Net.Sockets.SelectMode mode)
 {
     return(InternalSocket.Poll(microSeconds, mode));
 }
Пример #46
0
		public void Disposed7 ()
		{
			Socket s = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
			s.Close();

			s.Poll (100, 0);
		}
Пример #47
0
 private bool Readable(int aTimeout)
 {
     return(mSocket.Poll(aTimeout, SelectMode.SelectRead));
 }
Пример #48
0
 /// <summary>
 ///
 /// </summary>
 /// <param name="c"></param>
 /// <returns></returns>
 public static bool IsOnline(System.Net.Sockets.Socket c)
 {
     return(!((c.Poll(1000, System.Net.Sockets.SelectMode.SelectRead) && (c.Available == 0)) || !c.Connected));
 }
Пример #49
0
 public static bool IsSocketConnected(System.Net.Sockets.Socket s)
 {
     return(!((s.Poll(1000, SelectMode.SelectRead) && (s.Available == 0)) || !s.Connected));
 }
Пример #50
0
        private byte[] QueryServer(byte[] query,string serverIP)
        {
            byte[] retVal = null;

            try
            {
                IPEndPoint ipRemoteEndPoint = new IPEndPoint(IPAddress.Parse(serverIP),53);
                Socket udpClient = new Socket(AddressFamily.InterNetwork,SocketType.Dgram,ProtocolType.Udp);

                IPEndPoint ipLocalEndPoint = new IPEndPoint(IPAddress.Any, 0);
                EndPoint localEndPoint = (EndPoint)ipLocalEndPoint;
                udpClient.Bind(localEndPoint);

                udpClient.Connect(ipRemoteEndPoint);

                //send query
                udpClient.Send(query);

                // Wait until we have a reply
                if(udpClient.Poll(5*1000000,SelectMode.SelectRead)){
                    retVal = new byte[512];
                    udpClient.Receive(retVal);
                }

                udpClient.Close();
            }
            catch
            {
            }

            return retVal;
        }
Пример #51
0
        //
        //
        //
        public void Listen(SNS.AddressFamily addressFamily, int port, int timeoutSec, string stopFile, Dictionary <string, string> parameters)
        {
            DateTime startTime = System.DateTime.Now;

            SNS.Socket listenSocket = null;

            try
            {
                // delete stop file
                File.Delete(stopFile);

                // create the main listening socket
                listenSocket = new SNS.Socket(addressFamily, SNS.SocketType.Stream, SNS.ProtocolType.Tcp);

                // set socket options
                listenSocket.SetSocketOption(SNS.SocketOptionLevel.Socket, SNS.SocketOptionName.ReuseAddress, 1);
                listenSocket.SetSocketOption(SNS.SocketOptionLevel.Socket, SNS.SocketOptionName.Linger, new SNS.LingerOption(false, 0));
                listenSocket.SetSocketOption(SNS.SocketOptionLevel.Tcp, SNS.SocketOptionName.NoDelay, 1);

                // bind the listening socket
                if (addressFamily == SNS.AddressFamily.InterNetworkV6)
                {
                    listenSocket.Bind(new IPEndPoint(IPAddress.IPv6Any, port));
                }
                else
                if (addressFamily == SNS.AddressFamily.InterNetwork)
                {
                    listenSocket.Bind(new IPEndPoint(IPAddress.Any, port));
                }
                else
                {
                    throw new SocketException("Cant bind server socket. Unknown address family " + addressFamily.ToString());
                }

                // listen
                listenSocket.Listen(SocketConstants.SOCKET_BACKLOG);
                Console.WriteLine("SocketServer - listening on port [{0}] family [{1}]", port, addressFamily.ToString());

                // accept client connections - run in a thread pool thread
                using (MyThreadPoolManager tpm = new MyThreadPoolManager(50, 5000))                     // max 50 concurrent clients
                {
                    while (true)
                    {
                        // see if it is time to stop the server

                        if (File.Exists(stopFile))                             // stop listening if stop file exists
                        {
                            _stop = true;
                        }
                        else
                        if (timeoutSec > 0)                           // stop listening if server timed out
                        {
                            TimeSpan ts = System.DateTime.Now.Subtract(startTime);
                            if (ts.TotalSeconds >= timeoutSec)
                            {
                                _stop = true;
                            }
                        }

                        if (_stop)                           // time to go
                        {
                            tpm.Shutdown();
                            Console.WriteLine("SocketServer - listening on port [{0}] stopping...", port);
                            break;
                        }

                        if (listenSocket.Poll(200000, SNS.SelectMode.SelectRead))                             // ready to accept - 0.2 sec wait max
                        {
                            SNS.Socket clientSocket = listenSocket.Accept();

                            T tpi = new T();
                            tpi.Parameters = parameters;
                            tpi.SetRawSocket(clientSocket);
                            tpm.Queue(tpi);
                        }
                    }

                    //tpm.WaitUntilAllStarted() ; // servers alive until all queued sockets execute
                }
            }
            finally             // tidy up
            {
                Console.WriteLine("SocketServer [{0}] - listening on port [{1}] stopped", addressFamily, port);

                try
                {
                    listenSocket.Shutdown(SNS.SocketShutdown.Both);
                }
                catch (Exception) {}

                try
                {
                    listenSocket.Close();
                }
                catch (Exception) {}
            }
        } // end method