Ejemplo n.º 1
0
        /// <summary>
        /// Connect to server selected in autodetect list
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void buttonConnectDetected_Click(object sender, EventArgs e)
        {
            if (servers.Count <= 0 || listBoxServers.SelectedItem == null)
            {
                return;
            }

            if (socket != null)
            {
                socket.Close();
                socket = null;
            }

            Log("Connecting ...", null, "Connecting to server");

            socket              = new AsyncSocket();
            socket.WillConnect += new AsyncSocket.SocketWillConnect(socket_WillConnect);
            socket.DidConnect  += new AsyncSocket.SocketDidConnect(socket_DidConnect);
            socket.WillClose   += new AsyncSocket.SocketWillClose(socket_WillClose);
            socket.DidClose    += new AsyncSocket.SocketDidClose(socket_DidClose);
            socket.DidRead     += new AsyncSocket.SocketDidRead(socket_DidRead);
            socket.DidWrite    += new AsyncSocket.SocketDidWrite(socket_DidWrite);

            if (!socket.Connect(((NetService)listBoxServers.SelectedItem).HostName, (ushort)((NetService)listBoxServers.SelectedItem).Port))
            {
                Log(null, "Could not connect to server: AsyncSocket connect failed", "Could not connect to server");
                MessageBox.Show("Could not connect to server", "Error");
            }
        }
Ejemplo n.º 2
0
        /// <summary>
        /// Connect with manually entered info
        /// </summary>
        public void Connect()
        {
            if (socket != null)
            {
                socket.Close();
                socket = null;
            }

            Connected            = false;
            ConnectionFailed     = false;
            Authenticated        = false;
            AuthenticationFailed = false;

            Log.Info("Setting up WifiRemote connection to {0}:{1}", Address, Port);

            socket             = new AsyncSocket();
            socket.DidConnect += new AsyncSocket.SocketDidConnect(socket_DidConnect);
            socket.DidRead    += new AsyncSocket.SocketDidRead(socket_DidRead);
            socket.AllowMultithreadedCallbacks = true;
            if (!socket.Connect(Address, 8017))
            {
                Log.Warn("WifiRemoteClient: Could not connect to server, AsyncSocket connect failed");
                ConnectionFailed = true;
            }
        }
Ejemplo n.º 3
0
 private void cmdConnect_Click(object sender, EventArgs e)
 {
     if (cmdConnect.Text == "Connect")
     {
         _socket.Connect(txtServer.Text, long.Parse(txtPort.Text));
     }
     else
     {
         _socket.Send("close" + Environment.NewLine);
         System.Threading.Thread.Sleep(200);
         _socket.Close();
     }
 }
Ejemplo n.º 4
0
        public void Test_Write()
        {
            SocketWatcher w = new SocketWatcher(20);
            Address       a = new Address("127.0.0.1", 7001);

            a.Resolve();

            AsyncSocket listen = w.CreateListenSocket(this, a);

            listen.RequestAccept();

            AsyncSocket connect;

            lock (done)
            {
                connect = w.CreateConnectSocket(this, a);
                bool NoTimeout = Monitor.Wait(done, new TimeSpan(0, 0, 30));

                Assert.IsTrue(NoTimeout, "The read command didn't complete in time.");
                Assert.IsTrue(succeeded, errorMessage);
            }

            Assert.AreEqual("5678901234", success);
            connect.Close();
            listen.Close();
        }
Ejemplo n.º 5
0
        /// <summary>
        /// Stop the server and disconnect all clients.
        /// </summary>
        public void Stop()
        {
            if (!_isStarted)
            {
                Logger.Debug("WifiRemote: ListenSocket already stopped, ignoring stop command");
                return;
            }

            // Stop accepting connections
            _listenSocket.Close();

            // Stop any client connections
            lock (connectedSockets)
            {
                foreach (AsyncSocket socket in connectedSockets)
                {
                    //socket.CloseAfterReading();
                    socket.Close();
                }
            }

            _isStarted    = false;
            _listenSocket = null;

            Logger.Info("WifiRemote: Server stopped");
        }
Ejemplo n.º 6
0
        [Test] public void Test_Write()
        {
            AppDomain.CurrentDomain.UnhandledException += CurrentDomain_UnhandledException;
            a.Resolve();

            lock (start)
            {
                new Thread(Server).Start();
                Monitor.Wait(start);
            }

            try
            {
                lock (done)
                {
                    new Thread(Client).Start();
                    Monitor.Wait(done);

                    Assert.IsTrue(succeeded, errorMessage);
                }
            }
            finally
            {
                m_listen.Close();
            }

            Assert.AreEqual("5678901234", success);
        }
Ejemplo n.º 7
0
 /// <summary>
 /// Releases unmanaged and - optionally - managed resources
 /// </summary>
 /// <param name="disposing"><c>true</c> to release both managed and unmanaged resources; <c>false</c> to release only unmanaged resources.</param>
 protected virtual void Dispose(bool disposing)
 {
     {
         if (disposing)
         {
             // Release managed resources
             try {
                 if (AsyncSocket != null)
                 {
                     if (AsyncSocket.Connected)
                     {
                         AsyncSocket.Shutdown(SocketShutdown.Both);
                     }
                     if (AsyncStream != null)
                     {
                         AsyncStream.Close();
                         AsyncStream.Dispose();
                         AsyncStream = null;
                     }
                     AsyncSocket.Close();
                     AsyncSocket = null;
                 }
             }
             catch { }
         }
         // Release unmanaged resources
     }
 }
Ejemplo n.º 8
0
        /// <summary>

        /// Checks to see if any open sockets have disconnected and cleans them up.

        /// </summary>

        /// <param name="sender">The sender</param>

        /// <param name="e">Event args</param>

        void socketCleanupTimer_Elapsed(object sender, System.Timers.ElapsedEventArgs e)

        {
            this.socketCleanupTimer.Stop();

            int count = this.connectedSockets.Count;

            if (count > 0)

            {
                Queue <AsyncSocket> queue = new Queue <AsyncSocket>(this.connectedSockets.Count);

                lock (syncLock)

                {
                    foreach (ConnectedSocket cs in this.connectedSockets)

                    {
                        queue.Enqueue(cs.Socket);
                    }
                }



                while (queue.Count > 0)

                {
                    AsyncSocket socket = queue.Dequeue();

                    if (socket != null)

                    {
                        if (this.connectedSockets.Contains(socket))

                        {
                            bool safeToDisconnect = this.connectedSockets[socket].SafeToDisconnect;

                            if (safeToDisconnect && !socket.SmartConnected)

                            {
                                // socket is disconnected from the other end

                                socket.Close();
                            }
                        }
                    }
                }
            }

            if (this.isStarted)
            {
                this.socketCleanupTimer.Start();
            }
        }
Ejemplo n.º 9
0
        public void EnhancedSocket_Async_SendRecv()
        {
            AsyncSocket sockListen = null;
            AsyncSocket sock1      = null;
            AsyncSocket sock2      = null;
            int         cb;

            try
            {
                sockListen = new AsyncSocket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
                sockListen.ListenOn(new IPEndPoint(IPAddress.Any, 45001));

                sock1 = new AsyncSocket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
                sock1.Connect(new IPEndPoint(IPAddress.Loopback, 45001));

                sock2 = sockListen.Accept();

                for (int i = 0; i < 1000; i++)
                {
                    byte[] buf10 = new byte[10];
                    byte[] buf5  = new byte[5];

                    sock1.Send(new byte[] { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 });
                    cb = sock2.Receive(buf10);
                    Assert.AreEqual(10, cb);
                    CollectionAssert.AreEqual(new byte[] { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 }, buf10);

                    sock2.Send(new byte[] { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 });
                    cb = sock1.Receive(buf5);
                    Assert.AreEqual(5, cb);
                    CollectionAssert.AreEqual(new byte[] { 0, 1, 2, 3, 4 }, buf5);
                    cb = sock1.Receive(buf5);
                    Assert.AreEqual(5, cb);
                    CollectionAssert.AreEqual(new byte[] { 5, 6, 7, 8, 9 }, buf5);
                }
            }
            finally
            {
                if (sockListen != null)
                {
                    sockListen.Close();
                }

                if (sock1 != null)
                {
                    sock1.Close();
                }

                if (sock2 != null)
                {
                    sock2.Close();
                }
            }
        }
Ejemplo n.º 10
0
        private void startStopButton_Click(object sender, EventArgs e)
        {
            if (!isStarted)
            {
                // Start the echo server
                UInt16 port;
                UInt16.TryParse(portTextBox.Text, out port);

                // AsyncSocket.Accept will setup sockets for IPv4 and IPv6
                // You can connect using telnet

                Exception error;
                if (!listenSocket.Accept(port, out error))
                {
                    LogError("Error starting server: {0}", error);
                    return;
                }

                LogInfo("Echo server started on port {0}", listenSocket.LocalPort);
                isStarted = true;

                portTextBox.Enabled  = false;
                startStopButton.Text = "Stop";
            }
            else
            {
                // Stop accepting connections
                listenSocket.Close();

#if IS_MULTITHREADED
                // Stop any client connections
                lock (connectedSockets)
                {
                    foreach (AsyncSocket socket in connectedSockets)
                    {
                        socket.Close();
                    }
                }
#else
                // Stop any client connections
                foreach (AsyncSocket socket in connectedSockets)
                {
                    socket.Close();
                }
#endif

                LogInfo("Stopped Echo server");
                isStarted = false;

                portTextBox.Enabled  = true;
                startStopButton.Text = "Start";
            }
        }
Ejemplo n.º 11
0
 /// <summary>
 /// Close Socket
 /// </summary>
 /// <returns></returns>
 public bool CloseSocket()
 {
     try {
         _socket.Close();
         return(true);
     } catch (Exception ex) {
         if (ProcessError != null)
         {
             ProcessError(ex, "CloseSocket");
         }
         return(false);
     }
 }
Ejemplo n.º 12
0
        /// <summary>
        /// Handles the <see cref="AsyncSocket.DidAccept"/> event.
        /// </summary>
        /// <param name="sender">The listening <see cref="AsyncSocket"/></param>
        /// <param name="newSocket">The new <see cref="AsyncSocket"/> that was accepted</param>
        private void listenSocket_DidAccept(AsyncSocket sender, AsyncSocket newSocket)
        {
            LogInfo("Accepted client {0}:{1}", newSocket.RemoteAddress, newSocket.RemotePort);

            // check origin
            bool isLocal = IPAddress.IsLoopback(newSocket.RemoteAddress);
            bool isLAN   = Growl.CoreLibrary.IPUtilities.IsInSameSubnet(newSocket.LocalAddress, newSocket.RemoteAddress);

            if (!this.allowNetworkNotifications && !isLocal)
            {
                // remote connections not allowed - Should we return a GNTP error response? i think this is better (no reply at all)
                LogInfo("Blocked network request from '{0}'", newSocket.RemoteAddress);
                newSocket.Close();
                return;
            }

            bool passwordRequired = true;

            if (isLocal && !this.RequireLocalPassword)
            {
                passwordRequired = false;
            }
            else if (isLAN && !this.RequireLANPassword)
            {
                passwordRequired = false;
            }

            // SUPER IMPORTANT
            newSocket.AllowMultithreadedCallbacks = true;

            MessageHandler mh = new MessageHandler(this.serverName, this.passwordManager, passwordRequired, this.logFolder, this.loggingEnabled, this.allowNetworkNotifications, this.allowWebNotifications, this.allowSubscriptions);

            newSocket.DidClose     += new AsyncSocket.SocketDidClose(newSocket_DidClose);
            mh.MessageParsed       += new MessageHandler.MessageHandlerMessageParsedEventHandler(mh_MessageParsed);
            mh.Error               += new MessageHandler.MessageHandlerErrorEventHandler(mh_Error);
            mh.SocketUsageComplete += new MessageHandler.MessageHandlerSocketUsageCompleteEventHandler(mh_SocketUsageComplete);

            // lock here since in very rare cases, we can get flooded with so many incoming sockets that
            // the Add() throws an IndexOutOfRange exception (only ever happened when running GrowlHammer with loads of
            // simultaneous connections)
            lock (syncLock)
            {
                connectedSockets.Add(new ConnectedSocket(newSocket));
                connectedHandlers.Add(newSocket, mh);
            }

            mh.InitialRead(newSocket);
        }
Ejemplo n.º 13
0
        /// <summary>
        /// Stops the server and closes any open connections.
        /// </summary>
        public void Stop()
        {
            if (this.isStarted)
            {
                // Stop accepting connections
                listenSocket.Close();

                // Stop trying to clean up sockets
                this.socketCleanupTimer.Stop();

                // Stop any client connections
                int connected = 0;
                while (connectedSockets.Count > 0)
                {
                    // if this happens, then the socket could not be closed properly for some reason.
                    // we have no choice but to abandon the routine and force the stop anyway.
                    // (hopefully, dangling sockets will get cleaned up later by the GC)
                    if (connectedSockets.Count == connected)
                    {
                        this.connectedSockets.Clear();
                        this.connectedHandlers.Clear();
                        break;
                    }
                    connected = connectedSockets.Count;

                    // Call Disconnect on the socket,
                    // which will invoke the DidDisconnect method,
                    // which will remove the socket and handler from the list.

                    // (we have to use some trickery to a single item from the list without knowing the key)
                    AsyncSocket someSocket = connectedSockets[0].Socket;
                    if (someSocket != null)
                    {
                        someSocket.CloseImmediately();
                    }
                }

                if (this.bonjour != null)
                {
                    this.bonjour.Stop();
                }

                LogInfo("Stopped Growl server");
                isStarted = false;
            }
        }
Ejemplo n.º 14
0
 /// <summary>
 /// Disconnect
 /// </summary>
 public void Disconnect()
 {
     try {
         Socket.Close();
         Socket = new AsyncSocket();
         Socket.CouldNotConnect    += Socket_CouldNotConnect;
         Socket.SocketConnected    += Socket_SocketConnected;
         Socket.SocketDataArrival  += Socket_SocketDataArrival;
         Socket.SocketDisconnected += Socket_SocketDisconnected;
         Socket.SocketError        += Socket_SocketError;
         ConnectionsHelper.Update(Model);
     } catch (Exception ex) {
         if (ProcessError != null)
         {
             ProcessError(ex, "Disconnect");
         }
     }
 }
 public void StopSocket()
 {
     listenSocket.Close();
     listenSocket = null;
 }
Ejemplo n.º 16
0
        /// <summary>
        /// Handles the socket's DidRead event.
        /// </summary>
        /// <param name="socket">The <see cref="AsyncSocket"/></param>
        /// <param name="readBytes">Array of <see cref="byte"/>s that were read</param>
        /// <param name="tag">The tag identifying the read operation</param>
        protected override void SocketDidRead(AsyncSocket socket, byte[] readBytes, long tag)
        {
            try
            {
                int  numberOfBytesToReadNext = 0;
                long nextTag = 0;

                if (tag == CONNECTION_ESTABLISHED_TAG)
                {
                    // wait for a frame and read the first two bytes (containing the FIN, opcode, masking info, and payload length)
                    this.Socket.Read(2, TIMEOUT_UNLIMITED, BEGIN_FRAMING_TAG);
                }

                else if (tag == BEGIN_FRAMING_TAG)
                {
                    // reset this
                    this.AlreadyReceivedData.Remove(0, this.AlreadyReceivedData.Length);
                    this.ParserTag = 1; //TODO:

                    byte bFrameControl = readBytes[0];
                    byte bDataControl  = readBytes[1];

                    bool end = (bFrameControl & BYTE_FIN_FINAL) == BYTE_FIN_FINAL;
                    // TODO: handle fragments

                    if ((bFrameControl & BYTE_OPCODE_PONG) == BYTE_OPCODE_PONG)
                    {
                        // unsolicited Pong - we dont need to do anything
                    }
                    else if ((bFrameControl & BYTE_OPCODE_PING) == BYTE_OPCODE_PING)
                    {
                        // need to response with Pong
                        // TODO: handle this case
                    }
                    else if ((bFrameControl & BYTE_OPCODE_CLOSE) == BYTE_OPCODE_CLOSE)
                    {
                        // we dont really care about this
                    }
                    else if ((bFrameControl & BYTE_OPCODE_BINARY) == BYTE_OPCODE_BINARY)
                    {
                        // we dont really care about this
                    }
                    else if ((bFrameControl & BYTE_OPCODE_TEXT) == BYTE_OPCODE_TEXT)
                    {
                        // we dont really care about this
                    }
                    else if ((bFrameControl & BYTE_OPCODE_CONTINUATION) == BYTE_OPCODE_CONTINUATION)
                    {
                        // TODO: handle fragments
                    }

                    masked = (bDataControl & BYTE_MASKED_YES) == BYTE_MASKED_YES;
                    int length = (int)(bDataControl & ~BYTE_MASKED_YES);
                    if ((bDataControl & BYTE_LENGTH_16) == BYTE_LENGTH_16)
                    {
                        // read next two bytes for length
                        numberOfBytesToReadNext = 2;
                        nextTag = PAYLOAD_LENGTH_TAG;
                    }
                    else if ((bDataControl & BYTE_LENGTH_64) == BYTE_LENGTH_64)
                    {
                        // read next 8 bytes for length
                        numberOfBytesToReadNext = 8;
                        nextTag = PAYLOAD_LENGTH_TAG;
                    }
                    else
                    {
                        if (masked)
                        {
                            // read 4 byte masking key
                            numberOfBytesToReadNext = 4;
                            nextTag = MASKING_KEY_TAG;
                            payloadRemainingLength = length;
                        }
                        else
                        {
                            numberOfBytesToReadNext = length;
                            nextTag = GNTP_DATA_TAG;
                            payloadRemainingLength = 0;

                            // handle zero-length payload
                            if (numberOfBytesToReadNext == 0)
                            {
                                numberOfBytesToReadNext = 2;
                                nextTag = BEGIN_FRAMING_TAG;
                            }
                        }
                    }

                    // read next chunk of data
                    this.Socket.Read(numberOfBytesToReadNext, TIMEOUT_FRAME, nextTag);
                }
                else if (tag == PAYLOAD_LENGTH_TAG)
                {
                    long length = 0;
                    if (readBytes.Length == 2)
                    {
                        short s = BitConverter.ToInt16(readBytes, 0);
                        s      = System.Net.IPAddress.NetworkToHostOrder(s);
                        length = s;
                    }
                    else if (readBytes.Length == 8)
                    {
                        long l = BitConverter.ToInt64(readBytes, 0);
                        l      = System.Net.IPAddress.NetworkToHostOrder(l);
                        length = l;
                    }

                    if (masked)
                    {
                        // read 4 byte masking key
                        numberOfBytesToReadNext = 4;
                        nextTag = MASKING_KEY_TAG;
                        payloadRemainingLength = length;
                    }
                    else
                    {
                        if (length > int.MaxValue)
                        {
                            numberOfBytesToReadNext = int.MaxValue;
                            payloadRemainingLength  = length - numberOfBytesToReadNext;
                        }
                        else
                        {
                            numberOfBytesToReadNext = (int)length;
                            payloadRemainingLength  = 0;
                        }
                        nextTag = GNTP_DATA_TAG;

                        // handle zero-length payload
                        if (numberOfBytesToReadNext == 0)
                        {
                            numberOfBytesToReadNext = 2;
                            nextTag = BEGIN_FRAMING_TAG;
                        }
                    }

                    // read next chunk of data
                    this.Socket.Read(numberOfBytesToReadNext, TIMEOUT_FRAME, nextTag);
                }
                else if (tag == MASKING_KEY_TAG)
                {
                    mask = readBytes;

                    if (payloadRemainingLength > int.MaxValue)
                    {
                        numberOfBytesToReadNext = int.MaxValue;
                        payloadRemainingLength  = payloadRemainingLength - numberOfBytesToReadNext;
                    }
                    else
                    {
                        numberOfBytesToReadNext = (int)payloadRemainingLength;
                        payloadRemainingLength  = 0;
                    }
                    nextTag = GNTP_DATA_TAG;

                    // handle zero-length payload
                    if (numberOfBytesToReadNext == 0)
                    {
                        numberOfBytesToReadNext = 2;
                        nextTag = BEGIN_FRAMING_TAG;
                    }

                    // read next chunk of data
                    this.Socket.Read(numberOfBytesToReadNext, TIMEOUT_FRAME, nextTag);
                }
                else if (tag == GNTP_DATA_TAG)
                {
                    byte[] unmaskedBytes = null;
                    if (masked)
                    {
                        unmaskedBytes = new byte[readBytes.Length];
                        for (int i = 0; i < readBytes.Length; i++)
                        {
                            int  b            = i % 4;
                            byte unmaskedByte = (byte)(readBytes[i] ^ mask[b]);
                            unmaskedBytes[i] = unmaskedByte;
                        }
                    }
                    else
                    {
                        unmaskedBytes = readBytes;
                    }

                    parser.Parse(unmaskedBytes);

                    // normally we would want to kick off another socket.Read() here (looking for the next BEGIN_FRAME_TAG), but we currently only allow one request per socket connection
                }
                else
                {
                    // we can only get here if there was some unaccounted-for data. that is bad, so lets close the socket
                    socket.Close();
                }
            }
            catch (GrowlException gEx)
            {
                OnError(gEx.ErrorCode, gEx.Message, gEx.AdditionalInfo);
            }
            catch (Exception ex)
            {
                OnError(ErrorCode.INVALID_REQUEST, ErrorDescription.MALFORMED_REQUEST, ex.Message);
            }
        }
Ejemplo n.º 17
0
        private void asyncSocket_DidRead(AsyncSocket sender, byte[] data, long tag)
        {
            //	LogInfo("DidRead: {0}", tag);

            if (tag == HTTP_HEADERS)
            {
                // We read in one line of the http header response
                // Do we have the full http header yet?

                headerLength += data.Length;

                response.AppendBytes(data);
                if (!response.IsHeaderComplete())
                {
                    // We don't have a complete header yet
                    asyncSocket.Read(AsyncSocket.CRLFData, READ_HEADER_TIMEOUT, HTTP_HEADERS);
                }
                else
                {
                    LogInfo("Received Response: ({0} bytes)", headerLength);
                    LogMessage(response.ToString());

                    // Check the http status code
                    if (response.GetStatusCode() != 200)
                    {
                        // We only support status code 200 in this overly simple http client

                        LogError("HTTP status code is not \"200 OK\"");
                        LogError("Disconnecting...");

                        asyncSocket.Close();
                        return;
                    }

                    // Extract the Content-Length
                    String contentLength = response.GetHeaderFieldValue("Content-Length");
                    Int32.TryParse(contentLength, out fileSizeInBytes);

                    // Extract Transfer-Encoding
                    String transferEncoding     = response.GetHeaderFieldValue("Transfer-Encoding");
                    bool   usingChunkedTransfer = String.Equals(transferEncoding, "chunked", StringComparison.OrdinalIgnoreCase);

                    if (fileSizeInBytes > 0)
                    {
                        // Using traditional transfer

                        totalBytesReceived = 0;
                        asyncSocket.Read(fileSizeInBytes, READ_BODY_TIMEOUT, HTTP_BODY);
                    }
                    else if (usingChunkedTransfer)
                    {
                        // Using chunked transfer
                        // For more information on chunked transfer, see the "HTTP Made Really Easy" website:
                        // http://www.jmarshall.com/easy/http/

                        LogInfo("Using chunked transfer - Unable to use progress bar");

                        chunkedTransferStage = CHUNKED_STAGE_SIZE;
                        asyncSocket.Read(AsyncSocket.CRLFData, READ_CHUNKSIZE_TIMEOUT, HTTP_BODY_CHUNKED);
                    }
                    else
                    {
                        LogError("Unable to extract content length, and not using chunked transfer encoding!");
                        LogError("Disconnecting...");

                        asyncSocket.Close();
                        return;
                    }
                }
            }
            else if (tag == HTTP_BODY)
            {
                // Write the data to log
                try
                {
                    LogMessage(Encoding.UTF8.GetString(data));
                }
                catch
                {
                    LogError("Cannot convert chunk to UTF-8 string");
                }

                LogInfo("\r\nDownload complete");
                progressBar.Value = 100;

                TimeSpan ellapsed = DateTime.Now - startTime;
                LogInfo("\r\nTotal Time = {0:N} milliseconds", ellapsed.TotalMilliseconds);

                LogInfo("Disconnecting...");
                asyncSocket.Close();
            }
            else if (tag == HTTP_BODY_CHUNKED)
            {
                if (chunkedTransferStage == CHUNKED_STAGE_SIZE)
                {
                    // We have just read in a line with the size of the chunk data, in hex,
                    // possibly followed by a semicolon and extra parameters that can be ignored,
                    // and ending with CRLF
                    String sizeLine = Encoding.UTF8.GetString(data);

                    Int32 chunkSizeInBytes;
                    Int32.TryParse(sizeLine, System.Globalization.NumberStyles.HexNumber, null, out chunkSizeInBytes);

                    if (chunkSizeInBytes > 0)
                    {
                        // Don't forget about the trailing CRLF when downloading the data
                        chunkSizeInBytes += 2;

                        chunkedTransferStage = CHUNKED_STAGE_DATA;
                        asyncSocket.Read(chunkSizeInBytes, READ_BODY_TIMEOUT, tag);
                    }
                    else
                    {
                        chunkedTransferStage = CHUNKED_STAGE_FOOTER;
                        asyncSocket.Read(AsyncSocket.CRLFData, READ_FOOTER_TIMEOUT, tag);
                    }
                }
                else if (chunkedTransferStage == CHUNKED_STAGE_DATA)
                {
                    // Write the data to log (excluding trailing CRLF)
                    try
                    {
                        String str = Encoding.UTF8.GetString(data, 0, data.Length - 2);
                        LogMessage(str);
                    }
                    catch
                    {
                        LogError("Cannot convert chunk to UTF-8 string");
                    }

                    chunkedTransferStage = CHUNKED_STAGE_SIZE;
                    asyncSocket.Read(AsyncSocket.CRLFData, READ_CHUNKSIZE_TIMEOUT, tag);
                }
                else if (chunkedTransferStage == CHUNKED_STAGE_FOOTER)
                {
                    // The data we just downloaded is either a footer, or an empty line (single CRLF)
                    if (data.Length > 2)
                    {
                        LogInfo("Received HTTP Footer:");
                        LogInfo(Encoding.UTF8.GetString(data));

                        asyncSocket.Read(AsyncSocket.CRLFData, READ_FOOTER_TIMEOUT, tag);
                    }
                    else
                    {
                        LogInfo("\r\nDownload complete");

                        TimeSpan ellapsed = DateTime.Now - startTime;
                        LogInfo("\r\nTotal Time = {0:N} milliseconds", ellapsed.TotalMilliseconds);

                        LogInfo("Disconnecting...");
                        asyncSocket.Close();
                    }
                }
            }
        }
Ejemplo n.º 18
0
        public bool Connect(int timeout = 5000)
        {
            if (!isConnected)
            {
                lock (clientLock)
                {
                    setInstallationDirectory();
                    if (string.IsNullOrEmpty(enginePath))
                    {
                        return(false);
                    }

                    if (Process.GetProcessesByName(Path.GetFileNameWithoutExtension(enginePath)).Length == 0)
                    {
                        try
                        {
                            using (Process p = Process.Start(enginePath)) { }
                        }
                        catch (Exception ex)
                        {
                            log("Failed to start '{0}' - {1}", enginePath, ex.Message);
                            return(false);
                        }
                    }
                    else
                    {
                        log("AceStream already running");
                    }

                    string portFile = Path.Combine(installDir, "acestream.port");
                    int    tries    = timeout / 100;
                    while (!File.Exists(portFile))
                    {
                        tries--;
                        if (tries < 0)
                        {
                            return(false);
                        }
                        Thread.Sleep(100);
                    }

                    try
                    {
                        port = int.Parse(File.ReadAllText(portFile));
                        log("Using port {0}", port);
                    }
                    catch (Exception ex)
                    {
                        log("Failed to get port from '{0}' - {1}", portFile, ex.Message);
                        log("Using default port {0}", DEFAULT_PORT);
                        port = DEFAULT_PORT; //try default port
                    }

                    if (!socket.Connect(host, (ushort)port))
                    {
                        socket.Close();
                        log("Error connecting to {0}:{1)", host, port);
                        return(false);
                    }
                    isConnected = true;
                }
            }
            return(true);
        }
Ejemplo n.º 19
0
        public void Test_Ops()
        {
            SocketWatcher w = new SocketWatcher(20);
            Address       a = new Address("127.0.0.1", 7002);

            a.Resolve();
            AsyncSocket one   = w.CreateListenSocket(this, a);
            AsyncSocket two   = null;
            AsyncSocket three = one;
            AsyncSocket four  = two;

            Assert.IsTrue(one == three);
            Assert.IsTrue(two == four);
            Assert.IsTrue(one >= three);
            Assert.IsTrue(two >= four);
            Assert.IsTrue(one <= three);
            Assert.IsTrue(two <= four);
            Assert.IsTrue(one != two);
            Assert.IsTrue(two != one);
            Assert.IsTrue(one > two);
            Assert.IsTrue(one >= two);
            Assert.IsTrue(two < one);
            Assert.IsTrue(two <= one);

            two  = w.CreateListenSocket(this, a);
            four = two;
            Assert.IsTrue(one == three);
            Assert.IsTrue(two == four);
            Assert.IsTrue(one >= three);
            Assert.IsTrue(two >= four);
            Assert.IsTrue(one <= three);
            Assert.IsTrue(two <= four);
            Assert.IsTrue(one != two);
            Assert.IsTrue(two != one);

            int c = ((IComparable)one).CompareTo(two);

            Assert.IsTrue(c != 0);
            if (c == -1)
            {
                // one less than two
                Assert.IsTrue(one < two);
                Assert.IsTrue(one <= two);
                Assert.IsTrue(two > one);
                Assert.IsTrue(two >= one);
            }
            else if (c == 1)
            {
                // one greater than two
                Assert.IsTrue(one > two);
                Assert.IsTrue(one >= two);
                Assert.IsTrue(two < one);
                Assert.IsTrue(two <= one);
            }
            else
            {
                Assert.IsTrue(false);
            }
            one.Close();
            two.Close();
        }
Ejemplo n.º 20
0
 public void Disconnect()
 {
     socket.Close();
 }