Пример #1
0
    // 데이터를 서버로 전송(UDP)
    public int SendUnreliable <T>(IPacket <T> packet)
    {
        int sendSize = 0;

        if (transportUDP != null)
        {
            // 헤더 정보 생성
            PacketHeader     header     = new PacketHeader();
            HeaderSerializer serializer = new HeaderSerializer();

            // FIX THIS : 명시적 형변환 해줌. 소스코드와 다름
            header.packetId = (int)packet.GetPacketId();

            byte[] headerData = null;
            if (serializer.Serialize(header) == true)
            {
                headerData = serializer.GetSerializedData();
            }
            byte[] packetData = packet.GetData();

            byte[] data = new byte[headerData.Length + packetData.Length];

            int headerSize = Marshal.SizeOf(typeof(PacketHeader));
            Buffer.BlockCopy(headerData, 0, data, 0, headerSize);
            Buffer.BlockCopy(packetData, 0, data, headerSize, packetData.Length);

            sendSize = transportUDP.Send(data, data.Length);
        }
        return(sendSize);
    }
Пример #2
0
    // 데이터를 서버로 전송(TCP)
    public int SendReliable <T>(IPacket <T> packet)
    {
        int sendSize = 0;

        if (transportTCP != null)
        {
            // 모듈에서 사용할 헤더 정보를 생성합니다.
            PacketHeader     header     = new PacketHeader();
            HeaderSerializer serializer = new HeaderSerializer();

            //packetid = skill, moving 등등   moving은 2
            header.packetId = (int)packet.GetPacketId();

            byte[] headerData = null;
            if (serializer.Serialize(header) == true)
            {
                headerData = serializer.GetSerializedData();
            }

            byte[] packetData = packet.GetData();   //움직임 정보 들은 데이터
            byte[] data       = new byte[headerData.Length + packetData.Length];

            int headerSize = Marshal.SizeOf(typeof(PacketHeader));
            Buffer.BlockCopy(headerData, 0, data, 0, headerSize);
            Buffer.BlockCopy(packetData, 0, data, headerSize, packetData.Length);

            string str = "Send reliable packet[" + header.packetId + "]";

            sendSize = transportTCP.Send(data, data.Length);
        }

        return(sendSize);
    }
Пример #3
0
    //데이타를 전송하는 메소드. byte[] msg 를 newIPEndPoint로 전송한다.
    public void DataSend()
    {
        if (sendMsgs.Count > 0)
        {
            DataPacket packet;

            lock (sendLock)
            {
                packet = sendMsgs.Dequeue();
            }

            Debug.Log("메시지 보냄 : " + packet.endPoint);
            Debug.Log("메시지 보냄 (길이) : " + packet.headerData.length);
            Debug.Log("메시지 보냄 (출처) : " + packet.headerData.source);
            Debug.Log("메시지 보냄 (타입) : " + packet.headerData.id);

            HeaderSerializer headerSerializer = new HeaderSerializer();
            headerSerializer.Serialize(packet.headerData);

            byte[] header = headerSerializer.GetSerializedData();
            byte[] msg    = CombineByte(header, packet.msg);

            if (packet.headerData.source == (byte)DataHandler.Source.ClientSource)
            {
                udpSock.BeginSendTo(msg, 0, msg.Length, SocketFlags.None, packet.endPoint, new AsyncCallback(SendData), null);
            }
            else if (packet.headerData.source == (byte)DataHandler.Source.ServerSource)
            {
                tcpSock.Send(msg, 0, msg.Length, SocketFlags.None);
            }
        }
    }
Пример #4
0
    private byte[] CreatePacket <T>(IPacket <T> packet) // 패킷 만드는 메서드
    {
        byte[] packetData = packet.GetPacketData();     // 패킷의 데이터를 바이트화

        // 헤더 생성
        PacketHeader     header     = new PacketHeader();
        HeaderSerializer serializer = new HeaderSerializer();

        header.length = (short)packetData.Length;   // 패킷 데이터의 길이를 헤더에 입력
        header.id     = (byte)packet.GetPacketId(); // 패킷 데이터에서 ID를 가져와 헤더에 입력
        //Debug.Log("패킷 전송 - id : " + header.id.ToString() + " length :" + header.length);
        byte[] headerData = null;
        if (serializer.Serialize(header) == false)
        {
            return(null);
        }

        headerData = serializer.GetSerializedData(); // 헤더 데이터를 패킷 바이트로 변환


        byte[] data = new byte[headerData.Length + header.length]; // 최종 패킷의 길이 = 헤더패킷길이+내용패킷길이

        // 헤더와 내용을 하나의 배열로 복사
        int headerSize = Marshal.SizeOf(header.id) + Marshal.SizeOf(header.length);

        Buffer.BlockCopy(headerData, 0, data, 0, headerSize);
        Buffer.BlockCopy(packetData, 0, data, headerSize, packetData.Length);
        return(data);
    }
Пример #5
0
    public int Send <T>(int node, PacketId id, IPacket <T> packet)
    {
        int sendSize = 0;

        if (m_sessionTcp != null)
        {
            // 모듈에서 사용하는 헤더 정보 생성.
            PacketHeader     header     = new PacketHeader();
            HeaderSerializer serializer = new HeaderSerializer();

            header.packetId = id;

            byte[] headerData = null;
            if (serializer.Serialize(header) == true)
            {
                headerData = serializer.GetSerializedData();
            }
            byte[] packetData = packet.GetData();

            byte[] data = new byte[headerData.Length + packetData.Length];

            int headerSize = Marshal.SizeOf(typeof(PacketHeader));
            Buffer.BlockCopy(headerData, 0, data, 0, headerSize);
            Buffer.BlockCopy(packetData, 0, data, headerSize, packetData.Length);

            //string str = "Send Packet[" +  id  + "]";

            sendSize = m_sessionTcp.Send(node, data, data.Length);
        }

        return(sendSize);
    }
Пример #6
0
    // private method
    // create packet include header
    private byte[] CreatePacketStream <T, U>(Packet <T, U> packet)
    {
        // data iniialize
        byte[] packetData = packet.GetPacketData();

        PacketHeader     header     = new PacketHeader();
        HeaderSerializer serializer = new HeaderSerializer();

        // set header data
        header.length = (short)packetData.Length;
        header.id     = (byte)packet.GetPacketID();

        byte[] headerData = null;

        try
        {
            serializer.Serialize(header);
        }
        catch
        {
        }

        headerData = serializer.GetSerializeData();

        // header / packet data combine
        byte[] data = new byte[headerData.Length + packetData.Length];

        int headerSize = Marshal.SizeOf(header.id) + Marshal.SizeOf(header.length);

        Buffer.BlockCopy(headerData, 0, data, 0, headerSize);
        Buffer.BlockCopy(packetData, 0, data, headerSize, packetData.Length);

        return(data);
    }
Пример #7
0
    public int SendUnreliable <T>(IPacket <T> packet)
    {
        int sendSize = 0;

        if (m_udp != null)
        {
            // 모듈에서 사용할 헤더 정보를 생성합니다.
            PacketHeader     header     = new PacketHeader();
            HeaderSerializer serializer = new HeaderSerializer();

            header.packetId = packet.GetPacketId();

            byte[] headerData = null;
            if (serializer.Serialize(header) == true)
            {
                headerData = serializer.GetSerializedData();
            }
            byte[] packetData = packet.GetData();

            byte[] data = new byte[headerData.Length + packetData.Length];

            int headerSize = Marshal.SizeOf(typeof(PacketHeader));
            Buffer.BlockCopy(headerData, 0, data, 0, headerSize);
            Buffer.BlockCopy(packetData, 0, data, headerSize, packetData.Length);

            sendSize = m_udp.Send(data, data.Length);
        }

        return(sendSize);
    }
Пример #8
0
        /// <inheritdoc />
        public Task Send(string destinationAddress, TransportMessage message, ITransactionContext context)
        {
            var headers           = message.Headers;
            var now               = _rebusTime.Now;
            var priority          = headers.GetMessagePriority();
            var visible           = headers.GetInitialVisibilityDelay(now);
            var ttl               = headers.GetTtlSeconds();
            var serializedHeaders = HeaderSerializer.Serialize(headers);

            var command = context.GetSendCommand(_factory, _sendSql);

            // Lock is blocking, but we're not async anyway (Oracle provider is blocking).
            // As a bonus:
            // (1) Monitor is faster than SemaphoreSlim when there's no contention, which is usually the case;
            // (2) we don't need to allocate any extra object (command is private and not exposed to end-users).
            lock (command)
            {
                new SendCommand(command)
                {
                    Recipient  = destinationAddress,
                    Headers    = serializedHeaders,
                    Body       = message.Body,
                    Priority   = priority,
                    Now        = now,
                    Visible    = visible,
                    TtlSeconds = ttl,
                }
                .ExecuteNonQuery();
            }

            return(Task.CompletedTask);
        }
Пример #9
0
        public void Can_round_trip_headers()
        {
            if (Environment.OSVersion.Platform != PlatformID.Win32NT)
            {
                Assert.Ignore("ApprovalTests only works on Windows");
            }

            var input = new Dictionary <string, string>
            {
                {
                    "key 1",
                    "value 1"
                },
                {
                    "key 2",
                    "value 2"
                }
            };
            var serialized = HeaderSerializer.Serialize(input);

            TestApprover.Verify(serialized);
            var deserialize = HeaderSerializer.Deserialize(serialized);

            CollectionAssert.AreEquivalent(input, deserialize);
        }
Пример #10
0
    public void SendReliableToAll(PacketId id, byte[] data)
    {
        if (m_tcp != null)
        {
            // 모듈에서 사용할 헤더 정보를 생성합니다.
            PacketHeader     header     = new PacketHeader();
            HeaderSerializer serializer = new HeaderSerializer();

            header.packetId = id;

            byte[] headerData = null;
            if (serializer.Serialize(header) == true)
            {
                headerData = serializer.GetSerializedData();
            }

            byte[] pdata = new byte[headerData.Length + data.Length];

            int headerSize = Marshal.SizeOf(typeof(PacketHeader));
            Buffer.BlockCopy(headerData, 0, pdata, 0, headerSize);
            Buffer.BlockCopy(data, 0, pdata, headerSize, data.Length);

            string str = "Send reliable packet[" + header.packetId + "]";

            int sendSize = m_tcp.Send(pdata, pdata.Length);
            if (sendSize < 0)
            {
                // 송신 오류.
            }
        }
    }
Пример #11
0
    public int Send(PacketId id, byte[] data)
    {
        int sendSize = 0;

        if (m_tcp != null)
        {
            // 모듈에서 사용할 헤더 정보를 생성합니다.
            PacketHeader     header     = new PacketHeader();
            HeaderSerializer serializer = new HeaderSerializer();

            header.packetId = id;

            byte[] headerData = null;
            if (serializer.Serialize(header) == true)
            {
                headerData = serializer.GetSerializedData();
            }

            byte[] packetData = new byte[headerData.Length + data.Length];

            int headerSize = Marshal.SizeOf(typeof(PacketHeader));
            Buffer.BlockCopy(headerData, 0, packetData, 0, headerSize);
            Buffer.BlockCopy(data, 0, packetData, headerSize, data.Length);

            sendSize = m_tcp.Send(data, data.Length);
        }

        return(sendSize);
    }
Пример #12
0
        public Task Dispatch(TransportOperations outgoingMessages, TransportTransaction transaction, ContextBag context)
        {
            foreach (var operation in outgoingMessages.UnicastTransportOperations)
            {
                var    serializedHeaders = HeaderSerializer.Serialize(operation.Message.Headers);
                var    transportSettings = _settings.getTransportSettings();
                var    queueIndex        = operation.Destination.IndexOf("@", StringComparison.Ordinal);
                string to;
                string subject;
                if (queueIndex > 0)
                {
                    to      = operation.Destination.Substring(queueIndex + 1);
                    subject = $"NSB-MSG-{operation.Destination.Substring(0, queueIndex)}-{operation.Message.MessageId}";
                }
                else
                {
                    to      = transportSettings.ImapUser;
                    subject = $"NSB-MSG-{operation.Destination}-{operation.Message.MessageId}";
                }

                SmtpUtils.SendMail(
                    transportSettings.SmtpServer,
                    transportSettings.SmtpServerPort,
                    transportSettings.SmtpUser,
                    transportSettings.SmtpPassword,
                    transportSettings.ImapUser,
                    to,
                    subject,
                    serializedHeaders,
                    operation.Message.Body);
            }

            return(Task.CompletedTask);
        }
    public Task Dispatch(TransportOperations outgoingMessages, TransportTransaction transaction, ContextBag context)
    {
        foreach (var operation in outgoingMessages.UnicastTransportOperations)
        {
            var basePath        = BaseDirectoryBuilder.BuildBasePath(operation.Destination);
            var nativeMessageId = Guid.NewGuid().ToString();
            var bodyPath        = Path.Combine(basePath, ".bodies", $"{nativeMessageId}.xml");

            var dir = Path.GetDirectoryName(bodyPath);
            if (!Directory.Exists(dir))
            {
                Directory.CreateDirectory(dir);
            }
            File.WriteAllBytes(bodyPath, operation.Message.Body);

            var messageContents = new List <string>
            {
                bodyPath,
                HeaderSerializer.Serialize(operation.Message.Headers)
            };

            var messagePath = Path.Combine(basePath, $"{nativeMessageId}.txt");

            // write to temp file first so an atomic move can be done
            // this avoids the file being locked when the receiver tries to process it
            var tempFile = Path.GetTempFileName();
            File.WriteAllLines(tempFile, messageContents);
            File.Move(tempFile, messagePath);
        }

        return(TaskEx.CompletedTask);
    }
    public void DataHandle()
    {
        if (receiveMsgs.Count != 0)
        {
            //패킷을 Dequeue 한다 패킷 : 메시지 타입 + 메시지 내용
            tcpPacket = receiveMsgs.Dequeue();

            //타입과 내용을 분리한다
            msgType = tcpPacket.msg [0];
            msg     = new byte[tcpPacket.msg.Length - 1];
            Array.Copy(tcpPacket.msg, 1, msg, 0, msg.Length);

            //Dictionary에 등록된 델리게이트형 메소드에서 msg를 반환받는다.
            RecvNotifier     recvNotifier;
            HeaderSerializer serializer = new HeaderSerializer();
            HeaderData       headerData = new HeaderData();

            if (m_notifier.TryGetValue(msgType, out recvNotifier))
            {
                //send 할 id를 반환받음
                headerData.id = (byte)recvNotifier(msg);
            }
            else
            {
                Console.WriteLine("DataHandler::TryGetValue 에러" + msgType);
                headerData.id = (byte)ServerPacketId.None;
            }

            //상대방에게서 게임종료 패캣이 왔을 때는 따로 Send하지 않기 위해서
            if (headerData.id == (byte)ServerPacketId.None)
            {
                return;
            }

            //send할 메시지의 길이를 받음
            headerData.length = (short)msg.Length;

            //헤더 serialize
            try
            {
                serializer.Serialize(headerData);
                header = serializer.GetSerializedData();
            }
            catch
            {
                Console.WriteLine("DataHandler::HeaderSerialize 에러");
            }

            //헤더와 메시지 내용을 합쳐서 Send
            paket     = CombineByte(header, msg);
            tcpPacket = new TcpPacket(paket, tcpPacket.client);
            lock (sendLock)
            {
                sendMsgs.Enqueue(tcpPacket);
            }
        }
    }
Пример #15
0
    byte[] CreateResultPacket(byte[] msg, ServerPacketId Id)
    {
        HeaderData       headerData       = new HeaderData();
        HeaderSerializer HeaderSerializer = new HeaderSerializer();

        headerData.Id     = (byte)Id;
        headerData.length = (short)msg.Length;
        HeaderSerializer.Serialize(headerData);
        msg = CombineByte(HeaderSerializer.GetSerializedData(), msg);
        return(msg);
    }
Пример #16
0
        /// <summary>
        /// Performs persistence of a message to the underlying table
        /// </summary>
        /// <param name="destinationAddress">Address the message will be sent to</param>
        /// <param name="message">Message to be sent</param>
        /// <param name="connection">Connection to use for writing to the database</param>
        protected async Task InnerSend(string destinationAddress, TransportMessage message, IDbConnection connection)
        {
            var sendTable = TableName.Parse(destinationAddress);

            await myLock.WaitAsync(TimeSpan.FromSeconds(5));

            try
            {
                using (var command = connection.CreateCommand())
                {
                    command.CommandText = $@"
INSERT INTO {sendTable.QualifiedName}
(
    [headers],
    [body],
    [priority],
    [visible],
    [expiration]
)
VALUES
(
    @headers,
    @body,
    @priority,
    dateadd(ms, @visibilemilliseconds, dateadd(ss, @visibiletotalseconds, sysdatetimeoffset())),
    dateadd(ms, @ttlmilliseconds, dateadd(ss, @ttltotalseconds, sysdatetimeoffset()))
)";

                    var headers = message.Headers.Clone();

                    var priority = GetMessagePriority(headers);
                    var visible  = GetInitialVisibilityDelay(headers);
                    var ttl      = GetTtl(headers);

                    // must be last because the other functions on the headers might change them
                    var serializedHeaders = HeaderSerializer.Serialize(headers);

                    command.Parameters.Add("headers", SqlDbType.VarBinary, MathUtil.GetNextPowerOfTwo(serializedHeaders.Length)).Value = serializedHeaders;
                    command.Parameters.Add("body", SqlDbType.VarBinary, MathUtil.GetNextPowerOfTwo(message.Body.Length)).Value         = message.Body;
                    command.Parameters.Add("priority", SqlDbType.Int).Value             = priority;
                    command.Parameters.Add("visibiletotalseconds", SqlDbType.Int).Value = (int)visible.TotalSeconds;
                    command.Parameters.Add("visibilemilliseconds", SqlDbType.Int).Value = visible.Milliseconds;
                    command.Parameters.Add("ttltotalseconds", SqlDbType.Int).Value      = (int)ttl.TotalSeconds;
                    command.Parameters.Add("ttlmilliseconds", SqlDbType.Int).Value      = ttl.Milliseconds;

                    await command.ExecuteNonQueryAsync().ConfigureAwait(false);
                }
            }
            finally
            {
                myLock.Release();
            }
        }
Пример #17
0
    public void DataRequest(ClientPacketId Id)
    {
        //No Packet
        HeaderData       headerData       = new HeaderData();
        HeaderSerializer HeaderSerializer = new HeaderSerializer();

        headerData.Id = (byte)Id;
        HeaderSerializer.Serialize(headerData);
        byte[] msg = HeaderSerializer.GetSerializedData();

        sendMsg.Enqueue(msg);
    }
Пример #18
0
    public static byte[] CreateResultPacket(byte[] msg, P2PPacketId Id)
    {
        HeaderData       headerData       = new HeaderData();
        HeaderSerializer HeaderSerializer = new HeaderSerializer();

        headerData.Id     = (byte)Id;
        headerData.source = (byte)DataHandler.Source.ClientSource;
        headerData.length = (short)msg.Length;

        HeaderSerializer.Serialize(headerData);
        msg = DataHandler.CombineByte(HeaderSerializer.GetSerializedData(), msg);
        return(msg);
    }
Пример #19
0
        private void SendToFailoverQueue(TransportMessage transportMessage, string destination)
        {
            Message toSend = new Message();

            if (transportMessage.Body == null && transportMessage.BodyStream != null)
            {
                toSend.BodyStream = transportMessage.BodyStream;
            }
            else
            {
                MessageSerializer.Serialize(transportMessage.Body, toSend.BodyStream);
            }

            if (transportMessage.CorrelationId != null)
            {
                toSend.CorrelationId = transportMessage.CorrelationId;
            }
            else
            {
                toSend.CorrelationId              = toSend.Id;
                transportMessage.CorrelationId    = toSend.Id;
                transportMessage.IdForCorrelation = toSend.Id;
            }

            toSend.Recoverable   = transportMessage.Recoverable;
            toSend.ResponseQueue = new MessageQueue(GetFullPath(transportMessage.ReturnAddress));
            FillLabel(toSend, transportMessage);

            if (transportMessage.TimeToBeReceived < MessageQueue.InfiniteTimeout)
            {
                toSend.TimeToBeReceived = transportMessage.TimeToBeReceived;
            }

            if (transportMessage.Headers == null)
            {
                transportMessage.Headers = new List <HeaderInfo>();
            }

            transportMessage.Headers.Add(new HeaderInfo {
                Key = "destination", Value = destination
            });

            if (transportMessage.Headers != null && transportMessage.Headers.Count > 0)
            {
                MemoryStream stream = new MemoryStream();
                HeaderSerializer.Serialize(stream, transportMessage.Headers);
                toSend.Extension = stream.GetBuffer();
            }

            FailoverQueue.Send(toSend, GetTransactionTypeForSend());
        }
Пример #20
0
    byte[] CreateHeader <T>(IPacket <T> data, ClientPacketId Id)
    {
        byte[] msg = data.GetPacketData();

        HeaderData       headerData       = new HeaderData();
        HeaderSerializer headerSerializer = new HeaderSerializer();

        headerData.Id     = (byte)Id;
        headerData.length = (short)msg.Length;

        headerSerializer.Serialize(headerData);
        byte[] header = headerSerializer.GetSerializedData();

        return(header);
    }
Пример #21
0
    public void Logout()
    {
        //No Packet
        Debug.Log("로그아웃");
        HeaderData       headerData       = new HeaderData();
        HeaderSerializer HeaderSerializer = new HeaderSerializer();

        headerData.Id = (byte)ClientPacketId.Logout;
        HeaderSerializer.Serialize(headerData);
        byte[] msg = HeaderSerializer.GetSerializedData();

        sendMsg.Enqueue(msg);

        StartCoroutine(loadingManager.LoadScene(GameManager.Scene.Wait, GameManager.Scene.Login, 1.0f));
    }
        /// <inheritdoc />
        public async Task Send(string destinationAddress, TransportMessage message, ITransactionContext context)
        {
            using (await _sendBottleneck.Enter(CancellationToken.None))
            {
                var connection = await GetConnection(context);

                using (var command = connection.CreateCommand())
                {
                    command.CommandText = $@"
INSERT INTO {_tableName}
(
    recipient,
    headers,
    body,
    priority,
    visible,
    expiration
)
VALUES
(
    @recipient,
    @headers,
    @body,
    @priority,
    clock_timestamp() + @visible,
    clock_timestamp() + @ttlseconds
)";

                    var headers = message.Headers.Clone();

                    var priority = GetMessagePriority(headers);
                    var initialVisibilityDelay = new TimeSpan(0, 0, 0, GetInitialVisibilityDelay(headers));
                    var ttlSeconds             = new TimeSpan(0, 0, 0, GetTtlSeconds(headers));

                    // must be last because the other functions on the headers might change them
                    var serializedHeaders = HeaderSerializer.Serialize(headers);

                    command.Parameters.Add("recipient", NpgsqlDbType.Text).Value      = destinationAddress;
                    command.Parameters.Add("headers", NpgsqlDbType.Bytea).Value       = serializedHeaders;
                    command.Parameters.Add("body", NpgsqlDbType.Bytea).Value          = message.Body;
                    command.Parameters.Add("priority", NpgsqlDbType.Integer).Value    = priority;
                    command.Parameters.Add("visible", NpgsqlDbType.Interval).Value    = initialVisibilityDelay;
                    command.Parameters.Add("ttlseconds", NpgsqlDbType.Interval).Value = ttlSeconds;

                    await command.ExecuteNonQueryAsync();
                }
            }
        }
Пример #23
0
    //패킷의 헤더 생성
    byte[] CreateHeader <T>(Packet <T> data)
    {
        byte[] msg = data.GetPacketData();

        HeaderData       headerData       = new HeaderData();
        HeaderSerializer headerSerializer = new HeaderSerializer();

        headerData.length = (short)msg.Length;
        headerData.source = (byte)NetworkManager.Source.ClientSource;
        headerData.id     = (byte)data.GetPacketId();

        headerSerializer.Serialize(headerData);
        byte[] header = headerSerializer.GetSerializedData();

        return(header);
    }
Пример #24
0
        /// <summary>
        /// Called when the transport needs to send a message to a specified destination address.
        /// </summary>
        /// <param name="destinationAddress"></param>
        /// <param name="message"></param>
        /// <param name="context"></param>
        /// <returns></returns>
        public async Task Send(string destinationAddress, TransportMessage message, ITransactionContext context)
        {
            var connection = await GetConnection(context);

            using (var command = connection.CreateCommand())
            {
                command.CommandText = $@"
                    INSERT INTO `{_tableName}`
                    (
                        `recipient`,
                        `headers`,
                        `body`,
                        `priority`,
                        `visible`,
                        `expiration`,
                        `process_id`
                    )
                    VALUES
                    (
                        @recipient,
                        @headers,
                        @body,
                        @priority,
                        date_add(now(), INTERVAL @visible SECOND),
                        date_add(now(), INTERVAL @ttlseconds SECOND),
                        NULL
                    );";

                var headers = message.Headers.Clone();

                var priority = GetMessagePriority(headers);
                var initialVisibilityDelay = GetInitialVisibilityDelay(headers);
                var ttlSeconds             = GetTtlSeconds(headers);

                // must be last because the other functions on the headers might change them
                var serializedHeaders = HeaderSerializer.Serialize(headers);

                command.Parameters.Add(command.CreateParameter("recipient", DbType.String, destinationAddress));
                command.Parameters.Add(command.CreateParameter("headers", DbType.Binary, serializedHeaders));
                command.Parameters.Add(command.CreateParameter("body", DbType.Binary, message.Body));
                command.Parameters.Add(command.CreateParameter("priority", DbType.Int32, priority));
                command.Parameters.Add(command.CreateParameter("visible", DbType.Int32, initialVisibilityDelay));
                command.Parameters.Add(command.CreateParameter("ttlseconds", DbType.Int32, ttlSeconds));

                await command.ExecuteNonQueryAsync();
            }
        }
            public override async Task <WebSocketReceiveResult> ReceiveAsync(ArraySegment <byte> buffer, CancellationToken cancellationToken)
            {
                // indicate to the test that receive has been called - to we should now be connected
                TaskCompletionSource.SetResult("ReceiveAsync");

                // delay so we don't thrash, the header we return with End=false will cause an infinite receive loop
                await Task.Delay(1000);

                // send a valid header so we don't immediate get a deserialization exception that triggers disconnect
                var header = new Header()
                {
                    Type = PayloadTypes.Stream, Id = Guid.NewGuid(), PayloadLength = 0, End = false
                };
                var count = HeaderSerializer.Serialize(header, buffer.Array, buffer.Offset);

                return(new WebSocketReceiveResult(count, WebSocketMessageType.Binary, true));
            }
Пример #26
0
        /// <summary>
        /// Sends the given transport message to the specified logical destination address by adding it to the messages table.
        /// </summary>
        public async Task Send(string destinationAddress, TransportMessage message, ITransactionContext context)
        {
            var connection = await GetConnection(context);

            using (var command = connection.CreateCommand())
            {
                command.CommandText = string.Format(@"
INSERT INTO [{0}]
(
    [recipient],
    [headers],
    [body],
    [priority],
    [visible],
    [expiration]
)
VALUES
(
    @recipient,
    @headers,
    @body,
    @priority,
    dateadd(ss, @visible, getdate()),
    dateadd(ss, @ttlseconds, getdate())
)",
                                                    _tableName);

                var headers = message.Headers.Clone();

                var priority = GetMessagePriority(headers);
                var initialVisibilityDelay = GetInitialVisibilityDelay(headers);
                var ttlSeconds             = GetTtlSeconds(headers);

                // must be last because the other functions on the headers might change them
                var serializedHeaders = _headerSerializer.Serialize(headers);

                command.Parameters.Add("recipient", SqlDbType.NVarChar, RecipientColumnSize).Value = destinationAddress;
                command.Parameters.Add("headers", SqlDbType.VarBinary).Value = serializedHeaders;
                command.Parameters.Add("body", SqlDbType.VarBinary).Value    = message.Body;
                command.Parameters.Add("priority", SqlDbType.Int).Value      = priority;
                command.Parameters.Add("ttlseconds", SqlDbType.Int).Value    = ttlSeconds;
                command.Parameters.Add("visible", SqlDbType.Int).Value       = initialVisibilityDelay;

                await command.ExecuteNonQueryAsync();
            }
        }
Пример #27
0
        void InnerSend(string destinationAddress, TransportMessage message, ConnectionWrapper connection)
        {
            using (var command = connection.Connection.CreateCommand())
            {
                command.CommandText = $@"
                    INSERT INTO {_table}
                    (
                        recipient,
                        headers,
                        body,
                        priority,
                        visible,
                        expiration
                    )
                    VALUES
                    (
                        :recipient,
                        :headers,
                        :body,
                        :priority,
                        :now + :visible,
                        :now + :ttlseconds
                    )";

                var headers = message.Headers.Clone();

                var priority = GetMessagePriority(headers);
                var initialVisibilityDelay = new TimeSpan(0, 0, 0, GetInitialVisibilityDelay(headers));
                var ttlSeconds             = new TimeSpan(0, 0, 0, GetTtlSeconds(headers));

                // must be last because the other functions on the headers might change them
                var serializedHeaders = HeaderSerializer.Serialize(headers);

                command.BindByName = true;
                command.Parameters.Add(new OracleParameter("recipient", OracleDbType.Varchar2, destinationAddress, ParameterDirection.Input));
                command.Parameters.Add(new OracleParameter("headers", OracleDbType.Blob, serializedHeaders, ParameterDirection.Input));
                command.Parameters.Add(new OracleParameter("body", OracleDbType.Blob, message.Body, ParameterDirection.Input));
                command.Parameters.Add(new OracleParameter("priority", OracleDbType.Int32, priority, ParameterDirection.Input));
                command.Parameters.Add(new OracleParameter("visible", OracleDbType.IntervalDS, initialVisibilityDelay, ParameterDirection.Input));
                command.Parameters.Add(new OracleParameter("now", _rebusTime.Now.ToOracleTimeStamp()));
                command.Parameters.Add(new OracleParameter("ttlseconds", OracleDbType.IntervalDS, ttlSeconds, ParameterDirection.Input));

                command.ExecuteNonQuery();
            }
        }
Пример #28
0
        public void HeaderSerializer_SerializesToAscii()
        {
            var header = new Header()
            {
                Type          = PayloadTypes.Request,
                PayloadLength = 168,
                Id            = Guid.Parse("68e999ca-a651-40f4-ad8f-3aaf781862b4"),
                End           = true,
            };

            var       buffer = new byte[1024];
            const int offset = 0;

            var length = HeaderSerializer.Serialize(header, buffer, offset);

            var str = Encoding.ASCII.GetString(buffer, offset, length);

            Assert.Equal("A.000168.68e999ca-a651-40f4-ad8f-3aaf781862b4.1\n", str);
        }
Пример #29
0
    public Task Dispatch(TransportOperations outgoingMessages, ContextBag context)
    {
        foreach (UnicastTransportOperation transportOperation in outgoingMessages.UnicastTransportOperations)
        {
            string basePath        = BaseDirectoryBuilder.BuildBasePath(transportOperation.Destination);
            string nativeMessageId = Guid.NewGuid().ToString();
            string bodyPath        = Path.Combine(basePath, ".bodies", nativeMessageId) + ".xml";

            var dir = Path.GetDirectoryName(bodyPath);
            if (!Directory.Exists(dir))
            {
                Directory.CreateDirectory(dir);
            }
            File.WriteAllBytes(bodyPath, transportOperation.Message.Body);

            List <string> messageContents = new List <string>
            {
                bodyPath,
                HeaderSerializer.Serialize(transportOperation.Message.Headers)
            };

            DirectoryBasedTransaction transaction;

            string messagePath = Path.Combine(basePath, nativeMessageId) + ".txt";

            if (transportOperation.RequiredDispatchConsistency != DispatchConsistency.Isolated &&
                context.TryGet(out transaction))
            {
                transaction.Enlist(messagePath, messageContents);
            }
            else
            {
                string tempFile = Path.GetTempFileName();

                //write to temp file first so an atomic move can be done
                //this avoids the file being locked when the receiver tries to process it
                File.WriteAllLines(tempFile, messageContents);
                File.Move(tempFile, messagePath);
            }
        }

        return(TaskEx.CompletedTask);
    }
Пример #30
0
        /// <summary>
        /// Performs persistence of a message to the underlying table
        /// </summary>
        /// <param name="destinationAddress">Address the message will be sent to</param>
        /// <param name="message">Message to be sent</param>
        /// <param name="connection">Connection to use for writing to the database</param>
        protected async Task InnerSend(string destinationAddress, TransportMessage message, IDbConnection connection)
        {
            var sendTable = TableName.Parse(destinationAddress);

            using (var command = connection.CreateCommand())
            {
                command.CommandText = $@"
INSERT INTO {sendTable.QualifiedName}
(
    [headers],
    [body],
    [priority],
    [visible],
    [expiration]
)
VALUES
(
    @headers,
    @body,
    @priority,
    dateadd(ss, @visible, getdate()),
    dateadd(ss, @ttlseconds, getdate())
)";

                var headers = message.Headers.Clone();

                var priority = GetMessagePriority(headers);
                var initialVisibilityDelay = GetInitialVisibilityDelay(headers);
                var ttlSeconds             = GetTtlSeconds(headers);

                // must be last because the other functions on the headers might change them
                var serializedHeaders = HeaderSerializer.Serialize(headers);

                command.Parameters.Add("headers", SqlDbType.VarBinary, MathUtil.GetNextPowerOfTwo(serializedHeaders.Length)).Value = serializedHeaders;
                command.Parameters.Add("body", SqlDbType.VarBinary, MathUtil.GetNextPowerOfTwo(message.Body.Length)).Value         = message.Body;
                command.Parameters.Add("priority", SqlDbType.Int).Value   = priority;
                command.Parameters.Add("ttlseconds", SqlDbType.Int).Value = ttlSeconds;
                command.Parameters.Add("visible", SqlDbType.Int).Value    = initialVisibilityDelay;

                await command.ExecuteNonQueryAsync().ConfigureAwait(false);
            }
        }