protected override byte[] SerializeMessage(IScsMessage message)
        {
            var bytes = base.SerializeMessage(message);
            if (compress) bytes = CompressionManager.CompressGZip(bytes);
            if (encrypt) bytes = XXTEA.Encrypt(bytes, keys);

            return bytes;
        }
Exemple #2
0
        public byte[] GetBytes(IScsMessage message)
        {
            //Serialize the message to a byte array
            byte[] bytes = message is ScsTextMessage ? 
                Encoding.Default.GetBytes(((ScsTextMessage)message).Text) :
                ((ScsRawDataMessage)message).MessageData;

            return bytes;
        }
Exemple #3
0
 /// <summary>
 /// Overrides
 ///
 /// </summary>
 /// <param name="message"/>
 protected override void OnMessageReceived(IScsMessage message)
 {
     lock (this._receivingMessageQueue)
     {
         if (this._receivingMessageQueue.Count < this.IncomingMessageQueueCapacity)
         {
             this._receivingMessageQueue.Enqueue(message);
         }
         this._receiveWaiter.Set();
     }
 }
 /// <summary>
 ///     Sends a message to the remote application.
 /// </summary>
 /// <param name="message">Message to be sent</param>
 /// <param name="priority">Priority of message to send</param>
 protected override void SendMessagepublic(IScsMessage message, byte priority)
 {
     if (priority > 5)
     {
         _highPriorityBuffer.Enqueue(WireProtocol.GetBytes(message));
     }
     else
     {
         _lowPriorityBuffer.Enqueue(WireProtocol.GetBytes(message));
     }
 }
        /// <summary>
        /// This method is used to receive a specific type of message from remote application. It
        /// waits until a message is received or timeout occurs.
        /// </summary>
        /// <typeparam name="TMessage"></typeparam>
        /// <param name="timeout">
        /// Timeout value to wait if no message is received. Use -1 to wait indefinitely.
        /// </param>
        /// <returns>Received message</returns>
        public TMessage ReceiveMessage<TMessage>(int timeout) where TMessage : IScsMessage
        {
            IScsMessage receivedMessage = ReceiveMessage(timeout);
            if (!(receivedMessage is TMessage))
            {
                throw new Exception("Unexpected message received." +
                                    " Expected type: " + typeof(TMessage).Name +
                                    ". Received message type: " + receivedMessage.GetType().Name);
            }

            return (TMessage)receivedMessage;
        }
Exemple #6
0
 public byte[] GetBytes(IScsMessage message)
 {
     try
     {
         Cmd cmd = message as Cmd;
         return(_packer.pack(cmd).ToArray());
     }
     catch
     {
         return(null);
     }
 }
        protected override byte[] SerializeMessage(IScsMessage message)
        {
            byte msgTypeCodec = Convert.ToByte((int)MsgType.UnType_Msg);

            byte [] bytMsgId      = new byte [ConstData.tokenStringLength];
            byte [] bytReplyMsgId = new byte [ConstData.tokenStringLength];
            if (false == string.IsNullOrEmpty(message.MessageId))
            {
                bytMsgId = Encoding.ASCII.GetBytes(message.MessageId);
            }
            else
            {
                bytMsgId = Encoding.ASCII.GetBytes(ConstData.emptyGuidString);
            }

            if (false == string.IsNullOrEmpty(message.RepliedMessageId))
            {
                bytReplyMsgId = Encoding.ASCII.GetBytes(message.RepliedMessageId);
            }
            else
            {
                bytReplyMsgId = Encoding.ASCII.GetBytes(ConstData.emptyGuidString);
            }

            byte[] content = null;

            if (message is ScsRawDataMessage)
            {
                msgTypeCodec = (byte)MsgType.ScsRaw_Msg;
                content      = new byte[((ScsRawDataMessage)message).MessageData.Length];
                Buffer.BlockCopy(((ScsRawDataMessage)message).MessageData, 0, content, 0, content.Length);
            }
            else if (message is ScsTextMessage)
            {
                msgTypeCodec = (byte)MsgType.ScsText_Msg;
                content      = Encoding.UTF8.GetBytes(((ScsTextMessage)message).Text);
            }
            else if (message is ScsPingMessage)
            {
                msgTypeCodec = (byte)MsgType.ScsPing_Msg;
            }

            byte [] finalMsg = new byte [1 + ConstData.tokenStringLength * 2 + ((null != content)?(content.Length):(0))];
            finalMsg[0] = msgTypeCodec;
            Buffer.BlockCopy(bytMsgId, 0, finalMsg, 1, ConstData.tokenStringLength);
            Buffer.BlockCopy(bytReplyMsgId, 0, finalMsg, 1 + ConstData.tokenStringLength, ConstData.tokenStringLength);
            if (null != content)
            {
                Buffer.BlockCopy(content, 0, finalMsg, 1 + ConstData.tokenStringLength * 2, content.Length);
            }

            return(finalMsg);
        }
 public byte[] GetBytes(IScsMessage message)
 {
     try
     {
         Cmd cmd = message as Cmd;
         return _packer.pack(cmd).ToArray();
     }
     catch
     {
         return null;
     }
 }
Exemple #9
0
        /// <summary>
        /// This method is used to receive a specific type of message from remote application.
        ///             It waits until a message is received or timeout occurs.
        ///
        /// </summary>
        /// <param name="timeout">Timeout value to wait if no message is received.
        ///             Use -1 to wait indefinitely.
        ///             </param>
        /// <returns>
        /// Received message
        /// </returns>
        public TMessage ReceiveMessage <TMessage>(int timeout) where TMessage : IScsMessage
        {
            IScsMessage scsMessage = this.ReceiveMessage(timeout);

            if (!(scsMessage is TMessage))
            {
                throw new Exception("Unexpected message received. Expected type: " + typeof(TMessage).Name + ". Received message type: " + scsMessage.GetType().Name);
            }
            else
            {
                return((TMessage)scsMessage);
            }
        }
Exemple #10
0
 /// <summary>
 /// Sends response to the remote application that invoked a service method.
 /// </summary>
 /// <param name="requestMessage">Request message</param>
 /// <param name="returnValue">Return value to send</param>
 /// <param name="exception">Exception to send</param>
 private void SendInvokeResponse(IScsMessage requestMessage, object returnValue, ScsRemoteException exception)
 {
     try
     {
         _requestReplyMessenger.SendMessage(new ScsRemoteInvokeReturnMessage {
             RepliedMessageId = requestMessage.MessageId, ReturnValue = returnValue, RemoteException = exception
         });
     }
     catch (Exception ex)
     {
         _log.Error($"Exception:'{ex}',Message:'{ex.Message}',StackTrace:'{ex.StackTrace}'");
     }
 }
 public byte[] GetBytes(IScsMessage message)
 {
     var m = message as Protocols.GpsMessage;
     List<byte> bytes = new List<byte>();
     logger.Debug("Data {0}", BitConverter.ToString(m.Data));
     if (m.Data != null)
     {
         bytes.Add(0x02);
         bytes.Add(m.Data[m.Data.Length - 2]);
         bytes.Add(m.Data[m.Data.Length - 1]);
         m.Data = bytes.ToArray();
     }
     return bytes.ToArray();
 }
Exemple #12
0
 public void SendMessage(IPEndPoint remote, IScsMessage msg)
 {
     try
     {
         byte[] buffer = this.WireProtocol.GetBytes(msg);
         if (buffer != null)
             _udp_peer.SendData(buffer, remote);
     }
     catch (System.Exception ex)
     {
         EzLogger.GlobalLogger.warning(string.Format("{0}{2}{1}{2}",
             ex.Message, ex.StackTrace, Environment.NewLine));
     }
 }
Exemple #13
0
        /// <summary>
        /// Handles MessageReceived event of _communicationChannel object.
        /// </summary>
        /// <param name="sender">Source of event</param>
        /// <param name="e">Event arguments</param>
        private void CommunicationChannel_MessageReceived(object sender, MessageEventArgs e)
        {
            IScsMessage message = e.Message;

            if (message is ScsPingMessage)
            {
                _communicationChannel.SendMessage(new ScsPingMessage {
                    RepliedMessageId = message.MessageId
                }, 10);
                return;
            }

            OnMessageReceived(message);
        }
Exemple #14
0
        protected override byte[] SerializeMessage(IScsMessage message)
        {
            var bytes = base.SerializeMessage(message);

            if (compress)
            {
                bytes = CompressionManager.CompressGZip(bytes);
            }
            if (encrypt)
            {
                bytes = XXTEA.Encrypt(bytes, keys);
            }

            return(bytes);
        }
Exemple #15
0
        /// <summary>
        /// Sends a message to the remote application.
        /// </summary>
        /// <param name="message">Message to be sent</param>
        /// <exception cref="ArgumentNullException">Throws ArgumentNullException if message is null</exception>
        public void SendMessage(IScsMessage message)
        {
            if (message == null)
            {
                throw new ArgumentNullException("message");
            }

            try
            {
                SendMessageInternal(message);
            }
            catch (ObjectDisposedException)
            {
            }
        }
Exemple #16
0
 /// <summary>
 /// Sends response to the remote application that invoked a service method.
 ///
 /// </summary>
 /// <param name="requestMessage">Request message</param><param name="returnValue">Return value to send</param><param name="exception">Exception to send</param>
 private void SendInvokeResponse(IScsMessage requestMessage, object returnValue, ScsRemoteException exception)
 {
     try
     {
         RequestReplyMessenger <IScsClient> requestReplyMessenger = this._requestReplyMessenger;
         ScsRemoteInvokeReturnMessage       invokeReturnMessage1  = new ScsRemoteInvokeReturnMessage();
         invokeReturnMessage1.RepliedMessageId = requestMessage.MessageId;
         invokeReturnMessage1.ReturnValue      = returnValue;
         invokeReturnMessage1.RemoteException  = exception;
         ScsRemoteInvokeReturnMessage invokeReturnMessage2 = invokeReturnMessage1;
         requestReplyMessenger.SendMessage((IScsMessage)invokeReturnMessage2);
     }
     catch
     {
     }
 }
Exemple #17
0
 public void SendMessage(IPEndPoint remote, IScsMessage msg)
 {
     try
     {
         byte[] buffer = this.WireProtocol.GetBytes(msg);
         if (buffer != null)
         {
             _udp_peer.SendData(buffer, remote);
         }
     }
     catch (System.Exception ex)
     {
         EzLogger.GlobalLogger.warning(string.Format("{0}{2}{1}{2}",
                                                     ex.Message, ex.StackTrace, Environment.NewLine));
     }
 }
 /// <summary>
 /// Sends response to the remote application that invoked a service method.
 ///
 /// </summary>
 /// <param name="client">Client that sent invoke message</param><param name="requestMessage">Request message</param><param name="returnValue">Return value to send</param><param name="exception">Exception to send</param>
 private static void SendInvokeResponse(IMessenger client, IScsMessage requestMessage, object returnValue, ScsRemoteException exception)
 {
     try
     {
         IMessenger messenger = client;
         ScsRemoteInvokeReturnMessage invokeReturnMessage1 = new ScsRemoteInvokeReturnMessage();
         invokeReturnMessage1.RepliedMessageId = requestMessage.MessageId;
         invokeReturnMessage1.ReturnValue      = returnValue;
         invokeReturnMessage1.RemoteException  = exception;
         ScsRemoteInvokeReturnMessage invokeReturnMessage2 = invokeReturnMessage1;
         messenger.SendMessage((IScsMessage)invokeReturnMessage2);
     }
     catch
     {
     }
 }
 /// <summary>
 /// Sends response to the remote application that invoked a service method.
 /// </summary>
 /// <param name="client">Client that sent invoke message</param>
 /// <param name="requestMessage">Request message</param>
 /// <param name="returnValue">Return value to send</param>
 /// <param name="exception">Exception to send</param>
 private static void SendInvokeResponse(IMessenger client, IScsMessage requestMessage, object returnValue, ScsRemoteException exception)
 {
     try
     {
         client.SendMessage(
             new ScsRemoteInvokeReturnMessage
         {
             RepliedMessageId = requestMessage.MessageId,
             ReturnValue      = returnValue,
             RemoteException  = exception
         }, 10);
     }
     catch
     {
     }
 }
 /// <summary>
 /// Sends response to the remote application that invoked a service method.
 /// </summary>
 /// <param name="client">Client that sent invoke message</param>
 /// <param name="requestMessage">Request message</param>
 /// <param name="returnValue">Return value to send</param>
 /// <param name="exception">Exception to send</param>
 private static void SendInvokeResponse(IMessenger client, IScsMessage requestMessage, object returnValue, ScsRemoteException exception)
 {
     try
     {
         client.SendMessage(new ScsRemoteInvokeReturnMessage
         {
             RepliedMessageId = requestMessage.MessageId,
             ReturnValue      = returnValue,
             RemoteException  = exception
         }, 10);
     }
     catch (Exception ex)
     {
         Logger.Log.Error("Invoke response send failed", ex);
     }
 }
Exemple #21
0
 /// <summary>
 /// Sends response to the remote application that invoked a service method.
 /// </summary>
 /// <param name="requestMessage">Request message</param>
 /// <param name="returnValue">Return value to send</param>
 /// <param name="exception">Exception to send</param>
 private void SendInvokeResponse(IScsMessage requestMessage, object returnValue, ScsRemoteException exception)
 {
     try
     {
         _requestReplyMessenger.SendMessage(
             new ScsRemoteInvokeReturnMessage
         {
             RepliedMessageId = requestMessage.MessageId,
             ReturnValue      = returnValue,
             RemoteException  = exception
         });
     }
     catch
     {
     }
 }
 /// <summary>
 /// Serializes a message to a byte array to send to remote application.
 ///             This method is synchronized. So, only one thread can call it concurrently.
 /// 
 /// </summary>
 /// <param name="message">Message to be serialized</param><exception cref="T:Tera.NetworkApi.Communication.Scs.Communication.CommunicationException">Throws CommunicationException if message is bigger than maximum allowed message length.</exception>
 public byte[] GetBytes(IScsMessage message)
 {
     byte[] numArray = this.SerializeMessage(message);
     int length = numArray.Length;
     if (length > 134217728)
     {
         throw new CommunicationException("Message is too big (" + (object)length + " bytes). Max allowed length is " + (string)(object)134217728 + " bytes.");
     }
     else
     {
         byte[] buffer = new byte[length + 4];
         BinarySerializationProtocol.WriteInt32(buffer, 0, length);
         Array.Copy((Array)numArray, 0, (Array)buffer, 4, length);
         return buffer;
     }
 }
Exemple #23
0
        /// <summary>
        /// Handles MessageReceived event of _communicationChannel object.
        ///
        /// </summary>
        /// <param name="sender">Source of event</param><param name="e">Event arguments</param>
        private void CommunicationChannel_MessageReceived(object sender, MessageEventArgs e)
        {
            IScsMessage message = e.Message;

            if (message is ScsPingMessage)
            {
                ICommunicationChannel communicationChannel = this._communicationChannel;
                ScsPingMessage        scsPingMessage1      = new ScsPingMessage();
                scsPingMessage1.RepliedMessageId = message.MessageId;
                ScsPingMessage scsPingMessage2 = scsPingMessage1;
                communicationChannel.SendMessage((IScsMessage)scsPingMessage2);
            }
            else
            {
                this.OnMessageReceived(message);
            }
        }
Exemple #24
0
 /// <summary>
 /// Sends response to the remote application that invoked a service method.
 /// </summary>
 /// <param name="requestMessage">Request message</param>
 /// <param name="returnValue">Return value to send</param>
 /// <param name="exception">Exception to send</param>
 private void SendInvokeResponse(IScsMessage requestMessage, object returnValue, ScsRemoteException exception)
 {
     try
     {
         _requestReplyMessenger.SendMessage(
             new ScsRemoteInvokeReturnMessage
         {
             RepliedMessageId = requestMessage.MessageId,
             ReturnValue      = returnValue,
             RemoteException  = exception
         });
     }
     catch (Exception ex)
     {
         System.Diagnostics.Trace.Write($"SendInvokeResponse: {ex}");
     }
 }
        /// <summary>
        /// Serializes a message to a byte array to send to remote application.
        ///             This method is synchronized. So, only one thread can call it concurrently.
        ///
        /// </summary>
        /// <param name="message">Message to be serialized</param><exception cref="T:Hik.Communication.Scs.Communication.CommunicationException">Throws CommunicationException if message is bigger than maximum allowed message length.</exception>
        public byte[] GetBytes(IScsMessage message)
        {
            byte[] numArray = this.SerializeMessage(message);
            int    length   = numArray.Length;

            if (length > 134217728)
            {
                throw new CommunicationException("Message is too big (" + (object)length + " bytes). Max allowed length is " + (string)(object)134217728 + " bytes.");
            }
            else
            {
                byte[] buffer = new byte[length + 4];
                BinarySerializationProtocol.WriteInt32(buffer, 0, length);
                Array.Copy((Array)numArray, 0, (Array)buffer, 4, length);
                return(buffer);
            }
        }
Exemple #26
0
        /// <summary>
        /// Sends a message and waits a response for that message.
        /// </summary>
        /// <remarks>
        /// Response message is matched with RepliedMessageId property, so if any other message (that
        /// is not reply for sent message) is received from remote application, it is not considered
        /// as a reply and is not returned as return value of this method.
        ///
        /// MessageReceived event is not raised for response messages.
        /// </remarks>
        /// <param name="message">message to send</param>
        /// <param name="timeoutMilliseconds">Timeout duration as milliseconds.</param>
        /// <returns>Response message</returns>
        /// <exception cref="TimeoutException">
        /// Throws TimeoutException if can not receive reply message in timeout value
        /// </exception>
        /// <exception cref="CommunicationException">
        /// Throws CommunicationException if communication fails before reply message.
        /// </exception>
        public IScsMessage SendMessageAndWaitForResponse(IScsMessage message, int timeoutMilliseconds, byte priority)
        {
            // Create a waiting message record and add to list
            WaitingMessage waitingMessage = new WaitingMessage();

            lock (_syncObj)
            {
                _waitingMessages[message.MessageId] = waitingMessage;
            }

            try
            {
                // Send message
                Messenger.SendMessage(message, priority);

                // Wait for response
                waitingMessage.WaitEvent.Wait(timeoutMilliseconds);

                // Check for exceptions
                switch (waitingMessage.State)
                {
                case WaitingMessageStates.WaitingForResponse:
                    Logger.Error(new TimeoutException("Timeout occured. Can not received response."));
                    break;

                case WaitingMessageStates.Cancelled:
                    Logger.Error(new CommunicationException("Disconnected before response received."));
                    break;
                }

                // return response message
                return(waitingMessage.ResponseMessage);
            }
            finally
            {
                // Remove message from waiting messages
                lock (_syncObj)
                {
                    if (_waitingMessages.ContainsKey(message.MessageId))
                    {
                        _waitingMessages.Remove(message.MessageId);
                    }
                }
            }
        }
 /// <summary>
 /// Sends a message to the remote application.
 /// </summary>
 /// <param name="message">Message to be sent</param>
 protected override void SendMessagepublic(IScsMessage message)
 {
     try
     {
         if (_clientSocket.Connected)
         {
             // Create a byte array from message according to current protocol
             var messageBytes = WireProtocol.GetBytes(message);
             // Begin sending the data to the remote device
             _clientSocket.BeginSend(messageBytes, 0, messageBytes.Length, SocketFlags.None,
                                     new AsyncCallback(SendCallback), _clientSocket);
         }
     }
     catch (Exception e)
     {
         // disconnect
     }
 }
Exemple #28
0
        /// <summary>
        /// The sender of a message needs to provide a means to convert a (high-level) object into raw bytes
        /// that will be sent over the network connection.
        /// </summary>
        protected override byte[] SerializeMessage(IScsMessage message)
        {
            if (message is ScsRawDataMessage)
            {
                return (((ScsRawDataMessage)message).MessageData);
            }

            if (message is ScsTextMessage)
            {
                return Encoding.UTF8.GetBytes(((ScsTextMessage)message).Text);
            }

            if (message is ScsPingMessage)
            {
                //if the application idles, occasional ScsPingMessage(s) are being sent out
                //trying to serialize this as ScsTextMessage will throw an exception
            }

            return null;
        }
        /// <summary>
        /// Serializes a message to a byte array to send to remote application.
        /// This method is synchronized. So, only one thread can call it concurrently.
        /// </summary>
        /// <param name="message">Message to be serialized</param>
        /// <exception cref="CommunicationException">Throws CommunicationException if message is bigger than maximum allowed message length.</exception>
        public byte[] GetBytes(IScsMessage message)
        {
            //Serialize the message to a byte array
            var serializedMessage = SerializeMessage(message); 
           
            //Check for message length
            var messageLength = serializedMessage.Length;
            if (messageLength > MaxMessageLength)
            {
                throw new CommunicationException("Message is too big (" + messageLength + " bytes). Max allowed length is " + MaxMessageLength + " bytes.");
            }

            //Create a byte array including the length of the message (4 bytes) and serialized message content
            var bytes = new byte[messageLength + 4];
            WriteInt32(bytes, 0, messageLength);
            Array.Copy(serializedMessage, 0, bytes, 4, messageLength);

            //Return serialized message by this protocol
            return bytes;
        }
Exemple #30
0
        /// <summary>
        /// Send a Message and Wati for Reply
        /// </summary>
        /// <typeparam name="T">The expected Value</typeparam>
        /// <param name="msg">the message to send</param>
        /// <returns></returns>
        public static Task<IScsMessage> SendMessageWithReplyAsync(this IScsClient client, IScsMessage msg)
        {
            TaskCompletionSource<IScsMessage> tcs = new TaskCompletionSource<IScsMessage>();

            using (var requestReplyMessenger = new RequestReplyMessenger<IScsClient>(client))
            {
                requestReplyMessenger.Start(); //Start request/reply messenger

                //Send user message to the server and get response
                try {
                    var response = requestReplyMessenger.SendMessageAndWaitForResponse(msg);
                    tcs.SetResult(response);
                }
                catch (Exception ex)
                {
                    tcs.SetException(ex);
                }
            }

            return tcs.Task;
        }
Exemple #31
0
        /// <summary>
        /// Sends a message to the remote application.
        /// </summary>
        /// <param name="message">Message to be sent</param>
        protected override void SendMessageInternal(IScsMessage message)
        {
            //Send message
            var totalSent = 0;

            lock (_syncLock)
            {
                //Create a byte array from message according to current protocol
                var messageBytes = WireProtocol.GetBytes(message);
                //Send all bytes to the remote application
                while (totalSent < messageBytes.Length)
                {
                    try
                    {
                        var sent = _clientSocket.Send(messageBytes, totalSent, messageBytes.Length - totalSent, SocketFlags.None);
                        if (sent <= 0)
                        {
                            throw new CommunicationException("Message could not be sent via TCP socket. Only " + totalSent + " bytes of " + messageBytes.Length + " bytes are sent.");
                        }

                        totalSent += sent;
                    }
                    catch (SocketException ex)
                    {
                        if (ex.SocketErrorCode == SocketError.WouldBlock ||
                            ex.SocketErrorCode == SocketError.IOPending ||
                            ex.SocketErrorCode == SocketError.NoBufferSpaceAvailable)
                        {
                            // socket buffer is probably full, wait and try again
                            Thread.Sleep(30);
                        }
                    }
                }

                LastSentMessageTime = DateTime.Now;

                OnMessageSent(message);
            }
        }
Exemple #32
0
        /// <summary>
        /// Serializes a message to a byte array to send to remote application. This method is
        /// synchronized. So, only one thread can call it concurrently.
        /// </summary>
        /// <param name="message">Message to be serialized</param>
        /// <exception cref="CommunicationException">
        /// Throws CommunicationException if message is bigger than maximum allowed message length.
        /// </exception>
        public byte[] GetBytes(IScsMessage message)
        {
            // Serialize the message to a byte array
            byte[] serializedMessage = SerializeMessage(message);

            // Check for message length
            int messageLength = serializedMessage.Length;

            if (messageLength > MaxMessageLength)
            {
                throw new CommunicationException("Message is too big (" + messageLength + " bytes). Max allowed length is " + MaxMessageLength + " bytes.");
            }

            // Create a byte array including the length of the message (4 bytes) and serialized
            // message content
            byte[] bytes = new byte[messageLength + 4];
            WriteInt32(bytes, 0, messageLength);
            Array.Copy(serializedMessage, 0, bytes, 4, messageLength);

            // Return serialized message by this protocol
            return(bytes);
        }
Exemple #33
0
        protected override byte[] SerializeMessage(IScsMessage message)
        {
            //MemoryStream stream = new MemoryStream();
            //BinaryWriter writer = new BinaryWriter(stream, Encoding.UTF8);

            //uint nType = ((ScsTextMessage)message).RepliedMessageId;
            //string str = ((ScsTextMessage)message).Text;
            //int length = sizeof(uint) + Encoding.UTF8.GetBytes(str).Length;
            //byte[] retValue = new byte[length];
            //int index = 0;
            //Converter.IntToBytes(nType).CopyTo(retValue, index);
            //index += 4;
            //Encoding.UTF8.GetBytes(str).CopyTo(retValue, index);

            //writer.Write(nType);
            //writer.Write(str);
            //byte[] ret = stream.ToArray();
            //return retValue;
            UMessage msg = ((UMessage)message);

            return(msg.ToBytes());
        }
        /// <summary>
        /// Sends a message to the remote application.
        /// </summary>
        /// <param name="message">Message to be sent</param>
        protected override void SendMessagepublic(IScsMessage message)
        {
            //Send message
            var totalSent = 0;

            lock (_syncLock)
            {
                //Create a byte array from message according to current protocol
                var messageBytes = WireProtocol.GetBytes(message);
                //Send all bytes to the remote application
                while (totalSent < messageBytes.Length)
                {
                    if (_clientSocket.Connected)
                    {
                        var sent = 0;
                        try
                        {
                            sent = _clientSocket.Send(messageBytes, totalSent, messageBytes.Length - totalSent, SocketFlags.None);
                        }
                        catch (Exception e)
                        {
                            //annoying bug
                            Logger.Log.Error("A packet would have been sent to a disconnected client. IGNORE THIS.", e);
                        }

                        if (sent <= 0)
                        {
                            throw new CommunicationException("Message could not be sent via TCP socket. Only " + totalSent + " bytes of " + messageBytes.Length + " bytes are sent.");
                        }

                        totalSent += sent;
                    }
                }

                LastSentMessageTime = DateTime.Now;
                OnMessageSent(message);
            }
        }
Exemple #35
0
        /// <summary>
        /// Serializes a message to a byte array to send to remote application.
        /// This method is synchronized. So, only one thread can call it concurrently.
        /// </summary>
        /// <param name="message">Message to be serialized</param>
        /// <exception cref="CommunicationException">Throws CommunicationException if message is bigger than maximum allowed message length.</exception>
        public byte[] GetBytes(IScsMessage message)
        {
            byte[] serializedMessage = null;

            //Serialize the message to a byte array
            if (message.GetType().Name == "ScsMessage")
            {
                //Serialize the message to a byte array
                serializedMessage = Encoding.Default.GetBytes(message.ToString());
            }
            else
            {
                serializedMessage = (message as ScsRawDataMessage).MessageData;
            }

            //var serializedMessage = SerializeMessage(message);

            //Check for message length
            var messageLength = serializedMessage.Length;

            if (messageLength > MaxMessageLength)
            {
                throw new CommunicationException("Message is too big (" + messageLength + " bytes). Max allowed length is " + MaxMessageLength + " bytes.");
            }

            //Create a byte array including the length of the message (4 bytes) and serialized message content
            // var bytes = new byte[messageLength + 4];
            // WriteInt32(bytes, 0, messageLength);
            // Array.Copy(serializedMessage, 0, bytes, 4, messageLength);

            var bytes = new byte[messageLength + 4];

            WriteInt32(bytes, 0, messageLength);
            Array.Copy(serializedMessage, 0, bytes, 4, messageLength);

            //Return serialized message by this protocol
            return(bytes);
        }
Exemple #36
0
        /// <summary>
        /// Sends a message to the remote application.
        ///
        /// </summary>
        /// <param name="message">Message to be sent</param>
        protected override void SendMessageInternal(IScsMessage message)
        {
            int offset = 0;

            lock (this._syncLock)
            {
                byte[] local_1 = this.WireProtocol.GetBytes(message);
                while (offset < local_1.Length)
                {
                    int local_2 = this._clientSocket.Send(local_1, offset, local_1.Length - offset, SocketFlags.None);
                    if (local_2 <= 0)
                    {
                        throw new CommunicationException("Message could not be sent via TCP socket. Only " + (object)offset + " bytes of " + (string)(object)local_1.Length + " bytes are sent.");
                    }
                    else
                    {
                        offset += local_2;
                    }
                }
                this.LastSentMessageTime = DateTime.Now;
                this.OnMessageSent(message);
            }
        }
        /// <summary>
        /// Sends a message to the remote application.
        /// </summary>
        /// <param name="message">Message to be sent</param>
        protected override void SendMessageInternal(IScsMessage message)
        {
            //Send message
            var totalSent = 0;
            //lock (_syncLock)
            //{
                //Create a byte array from message according to current protocol
                var messageBytes = WireProtocol.GetBytes(message);
                //Send all bytes to the remote application
                while (totalSent < messageBytes.Length)
                {
                    var sent = _clientSocket.Send(messageBytes, totalSent, messageBytes.Length - totalSent, SocketFlags.None);
                    if (sent <= 0)
                    {
                        throw new CommunicationException("Message could not be sent via TCP socket. Only " + totalSent + " bytes of " + messageBytes.Length + " bytes are sent.");
                    }

                    totalSent += sent;
                }

                LastSentMessageTime = DateTime.Now;
                OnMessageSent(message);
            //}
        }
Exemple #38
0
        /// <summary>
        /// Sends a message to the remote application.
        /// </summary>
        /// <param name="message">Message to be sent</param>
        protected override void SendMessageInternal(IScsMessage message)
        {
            //Send message
            var totalSent = 0;

            lock (_syncLock)
            {
                //Create a byte array from message according to current protocol
                var messageBytes = WireProtocol.GetBytes(message);
                //Send all bytes to the remote application

                try
                {
                    _sslStream.Write(messageBytes, totalSent, messageBytes.Length);
                }
                catch
                {
                    throw new CommunicationException("Message could not be sent via SSL stream");
                }

                LastSentMessageTime = DateTime.Now;
                OnMessageSent(message);
            }
        }
        /// <summary>
        /// Sends a message to the remote application.
        /// </summary>
        /// <param name="message">Message to be sent</param>
        /// <exception cref="ArgumentNullException">Throws ArgumentNullException if message is null</exception>
        public void SendMessage(IScsMessage message)
        {
            if (message == null)
            {
                throw new ArgumentNullException("message");
            }

            SendMessageInternal(message);
        }
        /// <summary>
        /// Sends a message to the remote application.
        /// </summary>
        /// <param name="message">Message to be sent</param>
        protected override void SendMessageInternal(IScsMessage message)
        {
            //Send message
            var totalSent = 0;
            lock (_syncLock)
            {
                //Create a byte array from message according to current protocol
                var messageBytes = WireProtocol.GetBytes(message);
                //Send all bytes to the remote application
                while (totalSent < messageBytes.Length)
                {
                    var sent = _clientSocket.Send(messageBytes, totalSent, messageBytes.Length - totalSent, SocketFlags.None);
                    if (sent <= 0)
                    {
                        throw new CommunicationException("Message could not be sent via TCP socket. Only " + totalSent + " bytes of " + messageBytes.Length + " bytes are sent.");
                    }

                    totalSent += sent;
                }

                LastSentMessageTime = DateTime.Now;
                OnMessageSent(message);
            }
        }
 /// <summary>
 /// Sends a message to the remote application.
 /// 
 /// </summary>
 /// <param name="message">Message to be sent</param>
 protected override void SendMessageInternal(IScsMessage message)
 {
     int offset = 0;
     lock (this._syncLock)
     {
         byte[] local_1 = this.WireProtocol.GetBytes(message);
         while (offset < local_1.Length)
         {
             int local_2 = this._clientSocket.Send(local_1, offset, local_1.Length - offset, SocketFlags.None);
             if (local_2 <= 0)
                 throw new CommunicationException("Message could not be sent via TCP socket. Only " + (object)offset + " bytes of " + (string)(object)local_1.Length + " bytes are sent.");
             else
                 offset += local_2;
         }
         this.LastSentMessageTime = DateTime.Now;
         this.OnMessageSent(message);
     }
 }
Exemple #42
0
 /// <summary>
 /// Raises MessageSent event.
 /// 
 /// </summary>
 /// <param name="message">Received message</param>
 protected virtual void OnMessageSent(IScsMessage message)
 {
     EventHandler<MessageEventArgs> eventHandler = this.MessageSent;
     if (eventHandler == null)
         return;
     eventHandler((object)this, new MessageEventArgs(message));
 }
Exemple #43
0
 /// <summary>
 /// Raises MessageReceived event.
 /// 
 /// </summary>
 /// <param name="message">Received message</param>
 private void OnMessageReceived(IScsMessage message)
 {
     EventHandler<MessageEventArgs> eventHandler = this.MessageReceived;
     if (eventHandler == null)
         return;
     eventHandler((object)this, new MessageEventArgs(message));
 }
 /// <summary>
 /// Raises MessageReceived event.
 /// </summary>
 /// <param name="message">Received message</param>
 private void OnMessageReceived(IScsMessage message)
 {
     var handler = MessageReceived;
     if (handler != null)
     {
         handler(this, new MessageEventArgs(message));
     }
 }
 /// <summary>
 /// Sends a message to the remote application.
 /// </summary>
 /// <param name="message">Message to be sent</param>
 protected override void SendMessagepublic(IScsMessage message, byte priority)
 {
     if (priority > 5)
     {
         _highPriorityBuffer.Enqueue(WireProtocol.GetBytes(message));
     }
     else
     {
         _lowPriorityBuffer.Enqueue(WireProtocol.GetBytes(message));
     }
 }
 protected override byte[] SerializeMessage(IScsMessage message)
 {
     return Encoding.UTF8.GetBytes(((ScsTextMessage)message).Text);
 }
Exemple #47
0
        /// <summary>
        /// Sends a message to the server.
        /// </summary>
        /// <param name="message">Message to be sent</param>
        /// <exception cref="CommunicationStateException">Throws a CommunicationStateException if client is not connected to the server.</exception>
        public void SendMessage(IScsMessage message)
        {
            if (CommunicationState != CommunicationStates.Connected)
            {
                throw new CommunicationStateException("Client is not connected to the server.");
            }

            _communicationChannel.SendMessage(message);
        }
Exemple #48
0
 public byte[] GetBytes(IScsMessage message)
 {
     return ((OuterNetworkMessage)message).Data;
 }
 public byte[] GetBytes(IScsMessage message)
 {
     return ((SendPacket) message).Data;
 }
Exemple #50
0
 /// <summary>
 /// Creates a new MessageEventArgs object.
 /// </summary>
 /// <param name="message">Message object that is associated with this event</param>
 public MessageEventArgs(IScsMessage message, DateTime receivedTimestamp)
 {
     Message = message;
     ReceivedTimestamp = receivedTimestamp;
 }
Exemple #51
0
 /// <summary>
 /// Creates a new MessageEventArgs object.
 /// </summary>
 /// <param name="message">Message object that is associated with this event</param>
 public MessageEventArgs(IScsMessage message)
 {
     Message = message;
 }
Exemple #52
0
        protected virtual void OnMessageReceived(IPEndPoint remote, IScsMessage msg)
        {
            EzLogger.GlobalLogger.debug(string.Format("udp message from {0}: {1}", remote, msg));

            if (MessageReceived != null)
            {
                MessageReceived(remote, new MessageEventArgs(msg));
            }
        }
 /// <summary>
 /// Sends a message to the remote application.
 /// This method is overrided by derived classes to really send to message.
 /// </summary>
 /// <param name="message">Message to be sent</param>
 protected abstract void SendMessageInternal(IScsMessage message);
 /// <summary>
 /// This method is used to serialize a IScsMessage to a byte array.
 /// This method can be overrided by derived Classs to change serialization strategy.
 /// It is a couple with DeserializeMessage method and must be overrided together.
 /// </summary>
 /// <param name="message">Message to be serialized</param>
 /// <returns>
 /// Serialized message bytes.
 /// Does not include length of the message.
 /// </returns>
 protected virtual byte[] SerializeMessage(IScsMessage message)
 {
     using (var memoryStream = new MemoryStream())
     {
         new BinaryFormatter().Serialize(memoryStream, message);
         return memoryStream.ToArray();
     }
 }
 /// <summary>
 /// Raises MessageSent event.
 /// </summary>
 /// <param name="message">Received message</param>
 protected virtual void OnMessageSent(IScsMessage message)
 {
     var handler = MessageSent;
     if (handler != null)
     {
         handler(this, new MessageEventArgs(message));
     }
 }
Exemple #56
0
 /// <summary>
 /// Sends a message to the client.
 /// 
 /// </summary>
 /// <param name="message">Message to be sent</param>
 public void SendMessage(IScsMessage message)
 {
     this._communicationChannel.SendMessage(message);
 }
 public byte[] GetBytes(IScsMessage message)
 {
     Session.Encrypt(ref ((GameMessage) message).Data);
     return ((GameMessage) message).Data;
 }
Exemple #58
0
 public byte[] GetBytes(IScsMessage message)
 {
     return ((KeyMessage)message).Key;
 }
Exemple #59
0
 public void Send(IScsMessage msg)
 {
     _client.SendMessage(msg);
 }
        /// <summary>
        /// Sends a message to the remote application.
        /// </summary>
        /// <param name="message">Message to be sent</param>
        protected override void SendMessageInternal(IScsMessage message)
        {
            //Send message
            var totalSent = 0;
            lock (_syncLock)
            {
                //Create a byte array from message according to current protocol
                var messageBytes = WireProtocol.GetBytes(message);
                //Send all bytes to the remote application
                while (totalSent < messageBytes.Length)
                {
                    try
                    {
                        var sent = _clientSocket.Send(messageBytes, totalSent, messageBytes.Length - totalSent, SocketFlags.None);
                        if (sent <= 0)
                        {
                            throw new CommunicationException("Message could not be sent via TCP socket. Only " + totalSent + " bytes of " + messageBytes.Length + " bytes are sent.");
                        }

                        totalSent += sent;
                    }
                    catch (SocketException ex)
                    {
                        if (ex.SocketErrorCode == SocketError.WouldBlock ||
                            ex.SocketErrorCode == SocketError.IOPending ||
                            ex.SocketErrorCode == SocketError.NoBufferSpaceAvailable)
                        {
                            // socket buffer is probably full, wait and try again
                            Thread.Sleep(30);
                        }
                    }
                }

                LastSentMessageTime = DateTime.Now;

                OnMessageSent(message);
            }
        }