Example #1
0
        public Connection CreateTcpConnection(CommandProcessorContext context,
                                              Action <Connection, TcpPackage> handlePackage,
                                              Action <Connection> connectionEstablished         = null,
                                              Action <Connection, SocketError> connectionClosed = null,
                                              bool failContextOnError = true,
                                              IPEndPoint tcpEndPoint  = null)
        {
            var        connectionCreatedEvent = new ManualResetEventSlim(false);
            Connection typedConnection        = null;

            var connection = _connector.ConnectTo(
                Guid.NewGuid(),
                tcpEndPoint ?? TcpEndpoint,
                TcpConnectionManager.ConnectionTimeout,
                conn =>
            {
                // we execute callback on ThreadPool because on FreeBSD it can be called synchronously
                // causing deadlock
                ThreadPool.QueueUserWorkItem(_ =>
                {
                    if (!InteractiveMode)
                    {
                        Log.Info("TcpTypedConnection: connected to [{0}, L{1}, {2:B}].", conn.RemoteEndPoint, conn.LocalEndPoint, conn.ConnectionId);
                    }
                    if (connectionEstablished != null)
                    {
                        if (!connectionCreatedEvent.Wait(10000))
                        {
                            throw new Exception("TcpTypedConnection: creation took too long!");
                        }
                        connectionEstablished(typedConnection);
                    }
                });
            },
                (conn, error) =>
            {
                var message = string.Format("TcpTypedConnection: connection to [{0}, L{1}, {2:B}] failed. Error: {3}.",
                                            conn.RemoteEndPoint, conn.LocalEndPoint, conn.ConnectionId, error);
                Log.Error(message);

                if (connectionClosed != null)
                {
                    connectionClosed(null, error);
                }

                if (failContextOnError)
                {
                    context.Fail(reason: string.Format("Socket connection failed with error {0}.", error));
                }
            },
                verbose: !InteractiveMode);

            typedConnection = new Connection(connection, new RawMessageFormatter(_bufferManager), new LengthPrefixMessageFramer());
            typedConnection.ConnectionClosed +=
                (conn, error) =>
            {
                if (!InteractiveMode || error != SocketError.Success)
                {
                    Log.Info("TcpTypedConnection: connection [{0}, L{1}] was closed {2}",
                             conn.RemoteEndPoint, conn.LocalEndPoint,
                             error == SocketError.Success ? "cleanly." : "with error: " + error + ".");
                }

                if (connectionClosed != null)
                {
                    connectionClosed(conn, error);
                }
                else
                {
                    Log.Info("connectionClosed callback was null");
                }
            };
            connectionCreatedEvent.Set();

            typedConnection.ReceiveAsync(
                (conn, pkg) =>
            {
                var package       = new TcpPackage();
                bool validPackage = false;
                try
                {
                    package      = TcpPackage.FromArraySegment(new ArraySegment <byte>(pkg));
                    validPackage = true;

                    if (package.Command == TcpCommand.HeartbeatRequestCommand)
                    {
                        var resp = new TcpPackage(TcpCommand.HeartbeatResponseCommand, Guid.NewGuid(), null);
                        conn.EnqueueSend(resp.AsByteArray());
                        return;
                    }

                    handlePackage(conn, package);
                }
                catch (Exception ex)
                {
                    Log.InfoException(ex,
                                      "TcpTypedConnection: [{0}, L{1}] ERROR for {2}. Connection will be closed.",
                                      conn.RemoteEndPoint, conn.LocalEndPoint,
                                      validPackage ? package.Command as object : "<invalid package>");
                    conn.Close(ex.Message);

                    if (failContextOnError)
                    {
                        context.Fail(ex);
                    }
                }
            });

            return(typedConnection);
        }
Example #2
0
        public Connection CreateTcpConnection(CommandProcessorContext context, 
                                              Action<Connection, TcpPackage> handlePackage,
                                              Action<Connection> connectionEstablished = null,
                                              Action<Connection, SocketError> connectionClosed = null,
                                              bool failContextOnError = true)
        {
            var connectionCreatedEvent = new AutoResetEvent(false);
            Connection typedConnection = null;

            var connection = _connector.ConnectTo(
                TcpEndpoint,
                conn =>
                {
                    Log.Info("Connected to [{0}].", conn.EffectiveEndPoint);
                    if (connectionEstablished != null)
                    {
                        connectionCreatedEvent.WaitOne(500);
                        connectionEstablished(typedConnection);
                    }
                },
                (conn, error) =>
                {
                    var message = string.Format("Connection to [{0}] failed. Error: {1}.",
                                                conn.EffectiveEndPoint,
                                                error);
                    Log.Error(message);

                    if (connectionClosed != null)
                        connectionClosed(null, error);

                    if (failContextOnError)
                        context.Fail(reason: string.Format("Socket connection failed with error {0}.", error));
                });

            typedConnection = new Connection(connection, new RawMessageFormatter(_bufferManager), new LengthPrefixMessageFramer());
            typedConnection.ConnectionClosed +=
                (conn, error) =>
                {
                    Log.Info("Connection [{0}] was closed {1}",
                                conn.EffectiveEndPoint,
                                error == SocketError.Success ? "cleanly." : "with error: " + error + ".");

                    if (connectionClosed != null)
                        connectionClosed(conn, error);
                    else
                        Log.Info("connectionClosed callback was null");
                };
            connectionCreatedEvent.Set();

            typedConnection.ReceiveAsync(
                (conn, pkg) =>
                {
                    var package = new TcpPackage();
                    bool validPackage = false;
                    try
                    {
                        package = TcpPackage.FromArraySegment(new ArraySegment<byte>(pkg));
                        validPackage = true;

                        if (package.Command == TcpCommand.HeartbeatRequestCommand)
                        {
                            var resp = new TcpPackage(TcpCommand.HeartbeatResponseCommand, Guid.NewGuid(), null);
                            conn.EnqueueSend(resp.AsByteArray());
                            return;
                        }

                        handlePackage(conn, package);
                    }
                    catch (Exception ex)
                    {
                        Log.InfoException(ex,
                                          "[{0}] ERROR for {1}. Connection will be closed.",
                                          conn.EffectiveEndPoint,
                                          validPackage ? package.Command as object : "<invalid package>");
                        conn.Close();

                        if (failContextOnError)
                            context.Fail(ex);
                    }
                });

            return typedConnection;
        }
Example #3
0
        public Connection CreateTcpConnection(CommandProcessorContext context, 
                                              Action<Connection, TcpPackage> handlePackage,
                                              Action<Connection> connectionEstablished = null,
                                              Action<Connection, SocketError> connectionClosed = null,
                                              bool failContextOnError = true,
                                              IPEndPoint tcpEndPoint = null)
        {
            var connectionCreatedEvent = new ManualResetEventSlim(false);
            Connection typedConnection = null;

            var connection = _connector.ConnectTo(
                Guid.NewGuid(),
                tcpEndPoint ?? TcpEndpoint,
                conn =>
                {
                    // we execute callback on ThreadPool because on FreeBSD it can be called synchronously
                    // causing deadlock
                    ThreadPool.QueueUserWorkItem(_ => 
                    {
                        if (!InteractiveMode)
                            Log.Info("Connected to [{0}, L{1}].", conn.RemoteEndPoint, conn.LocalEndPoint);
                        if (connectionEstablished != null)
                        {
                            if (!connectionCreatedEvent.Wait(10000))
                                throw new Exception("TcpTypedConnection creation took too long!");
                            connectionEstablished(typedConnection);
                        }
                    });
                },
                (conn, error) =>
                {
                    var message = string.Format("Connection to [{0}, L{1}] failed. Error: {2}.",
                                                conn.RemoteEndPoint, conn.LocalEndPoint, error);
                    Log.Error(message);

                    if (connectionClosed != null)
                        connectionClosed(null, error);

                    if (failContextOnError)
                        context.Fail(reason: string.Format("Socket connection failed with error {0}.", error));
                },
                verbose: !InteractiveMode);

            typedConnection = new Connection(connection, new RawMessageFormatter(_bufferManager), new LengthPrefixMessageFramer());
            typedConnection.ConnectionClosed +=
                (conn, error) =>
                {
                    if (!InteractiveMode || error != SocketError.Success)
                    {
                        Log.Info("Connection [{0}, L{1}] was closed {2}",
                                 conn.RemoteEndPoint, conn.LocalEndPoint,
                                 error == SocketError.Success ? "cleanly." : "with error: " + error + ".");
                    }

                    if (connectionClosed != null)
                        connectionClosed(conn, error);
                    else
                        Log.Info("connectionClosed callback was null");
                };
            connectionCreatedEvent.Set();

            typedConnection.ReceiveAsync(
                (conn, pkg) =>
                {
                    var package = new TcpPackage();
                    bool validPackage = false;
                    try
                    {
                        package = TcpPackage.FromArraySegment(new ArraySegment<byte>(pkg));
                        validPackage = true;

                        if (package.Command == TcpCommand.HeartbeatRequestCommand)
                        {
                            var resp = new TcpPackage(TcpCommand.HeartbeatResponseCommand, Guid.NewGuid(), null);
                            conn.EnqueueSend(resp.AsByteArray());
                            return;
                        }

                        handlePackage(conn, package);
                    }
                    catch (Exception ex)
                    {
                        Log.InfoException(ex,
                                          "[{0}, L{1}] ERROR for {2}. Connection will be closed.",
                                          conn.RemoteEndPoint, conn.LocalEndPoint,
                                          validPackage ? package.Command as object : "<invalid package>");
                        conn.Close(ex.Message);

                        if (failContextOnError)
                            context.Fail(ex);
                    }
                });

            return typedConnection;
        }
Example #4
0
        public Connection CreateTcpConnection(CommandProcessorContext context,
                                              Action <Connection, TcpPackage> handlePackage,
                                              Action <Connection> connectionEstablished         = null,
                                              Action <Connection, SocketError> connectionClosed = null,
                                              bool failContextOnError = true)
        {
            var        connectionCreatedEvent = new AutoResetEvent(false);
            Connection typedConnection        = null;

            var connection = _connector.ConnectTo(
                TcpEndpoint,
                conn =>
            {
                Log.Info("Connected to [{0}].", conn.EffectiveEndPoint);
                if (connectionEstablished != null)
                {
                    connectionCreatedEvent.WaitOne(500);
                    connectionEstablished(typedConnection);
                }
            },
                (conn, error) =>
            {
                var message = string.Format("Connection to [{0}] failed. Error: {1}.",
                                            conn.EffectiveEndPoint,
                                            error);
                Log.Error(message);

                if (connectionClosed != null)
                {
                    connectionClosed(null, error);
                }

                if (failContextOnError)
                {
                    context.Fail(reason: string.Format("Socket connection failed with error {0}.", error));
                }
            });

            typedConnection = new Connection(connection, new RawMessageFormatter(_bufferManager), new LengthPrefixMessageFramer());
            typedConnection.ConnectionClosed +=
                (conn, error) =>
            {
                Log.Info("Connection [{0}] was closed {1}",
                         conn.EffectiveEndPoint,
                         error == SocketError.Success ? "cleanly." : "with error: " + error + ".");

                if (connectionClosed != null)
                {
                    connectionClosed(conn, error);
                }
                else
                {
                    Log.Info("connectionClosed callback was null");
                }
            };
            connectionCreatedEvent.Set();

            typedConnection.ReceiveAsync(
                (conn, pkg) =>
            {
                var package       = new TcpPackage();
                bool validPackage = false;
                try
                {
                    package      = TcpPackage.FromArraySegment(new ArraySegment <byte>(pkg));
                    validPackage = true;

                    if (package.Command == TcpCommand.HeartbeatRequestCommand)
                    {
                        var resp = new TcpPackage(TcpCommand.HeartbeatResponseCommand, Guid.NewGuid(), null);
                        conn.EnqueueSend(resp.AsByteArray());
                        return;
                    }

                    handlePackage(conn, package);
                }
                catch (Exception ex)
                {
                    Log.InfoException(ex,
                                      "[{0}] ERROR for {1}. Connection will be closed.",
                                      conn.EffectiveEndPoint,
                                      validPackage ? package.Command as object : "<invalid package>");
                    conn.Close();

                    if (failContextOnError)
                    {
                        context.Fail(ex);
                    }
                }
            });

            return(typedConnection);
        }