当前位置: 首页>>代码示例>>C#>>正文


C# Message.Serialize方法代码示例

本文整理汇总了C#中Message.Serialize方法的典型用法代码示例。如果您正苦于以下问题:C# Message.Serialize方法的具体用法?C# Message.Serialize怎么用?C# Message.Serialize使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在Message的用法示例。


在下文中一共展示了Message.Serialize方法的10个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。

示例1: Main

        /// <summary>
        /// This is a simple demonstration of zeroMQ sockets using netMQ and protocol-buffer  
        /// This code demonstrates two things
        /// 
        /// 1. Use of zeroMQ REQUEST-RESPONSE socket using NetMQ library
        /// 2. Serialization and Deserialization using protocol-buf library
        /// 
        /// NOTE: Request-Response pattern is strictly sequential
        /// </summary>
        /// <param name="args"></param>
        static void Main(string[] args)
        {
            const string serverAddress = "tcp://localhost:5556";
            const string serverIdentifier = "Response Server";

            using (var context = NetMQContext.Create())
            using (var server = context.CreateResponseSocket())
            using (var client = context.CreateRequestSocket())
            {
                // Bind the server to a local TCP address
                // Server is the stable infrastructure and that should BIND
                server.Bind(serverAddress);

                // Connect the client to the server. Client is dynamic so it CONNECTs to the address
                client.Connect(serverAddress);

                {
                    var clientMsg = new Message();
                    clientMsg.initMessage("Request Client1", serverIdentifier, "hello", "getting introduced");
                    Console.WriteLine("Client sending message: {0}", clientMsg.ToString());

                    // Send a message from the client socket
                    client.SendFrame(clientMsg.Serialize());
                }

                // Receive the message from the server socket
                {
                    byte[] rawmsg = server.ReceiveFrameBytes();
                    if (rawmsg != null && rawmsg.Length > 0)
                    {
                        var receivedMsg = Message.Deserialize(rawmsg);
                        Console.WriteLine("Server Received Message From Client: {0}", receivedMsg.ToString());

                        var serverMsg = new Message();
                        serverMsg.initMessage(serverIdentifier, receivedMsg.Source, "hello " + receivedMsg.Source, "Server has a new connection!");

                        Console.WriteLine("Server sending message: {0}", serverMsg.ToString());
                        // Send a response back from the server
                        server.SendFrame(serverMsg.Serialize());

                    }

                }

                // Now client should receive the message
                {
                    byte[] rawmsg = client.ReceiveFrameBytes();
                    if (rawmsg != null && rawmsg.Length > 0)
                    {

                        var receivedMsg = Message.Deserialize(rawmsg);
                        Console.WriteLine("Message From Server: {0}", receivedMsg.ToString());
                    }
                }

                Console.WriteLine("Press any key to exit ...");
                Console.ReadKey();
            }
        }
开发者ID:bbcCorp,项目名称:NetMQDemo,代码行数:69,代码来源:Program.cs

示例2: MemoryStream

        void INetChannel.Send(Message msg)
        {
            MemoryStream stream = new MemoryStream();
            BinaryWriter writer = new BinaryWriter(stream);
            msg.Serialize(writer);
            var arr = new byte[stream.Position];
            Array.Copy(stream.GetBuffer(), arr, stream.Position);

            var data = new Dictionary<byte, object>();
            data[0] = arr;
            bool isReliable = msg.Reliability == MessageReliability.Reliable || msg.Reliability == MessageReliability.ReliableOrdered;
            _photon.OpCustom(42, data, isReliable); //Photon does not allow to send raw messages so send dummy operation instead
        }
开发者ID:tlotter,项目名称:MassiveOnlineUniversalServerEngine,代码行数:13,代码来源:PhotonNetClient.cs

示例3: Main

        static void Main(string[] args)
        {
            const string publisherAddress = "tcp://localhost:12345";
            const string publisherIdentifier = "Response Server";

            using (var context = NetMQContext.Create())
            using (var publisherSocket = context.CreatePublisherSocket())
            {

                Console.WriteLine("Publisher socket binding...");
                publisherSocket.Options.SendHighWatermark = 1000;
                publisherSocket.Bind(publisherAddress);

                Random rnd = new Random();
                long msgCount = 0;

                while(true)
                {
                    // Give a chance for subscribers to join before firing off messages
                    Thread.Sleep(rnd.Next(10000));

                    // Fire off 100 messages to all registered subscribers
                    for (var i = 0; i < 100; i++)
                    {
                        // Randomly generate 5 types of messages to replicate 5 types of subscribers
                        var randomizedTopic = (rnd.Next() % 5) + 1;
                        var subscriberType = String.Format("Subscribers Type:{0}", randomizedTopic);
                        var messageType = String.Format("MessageType:{0}", randomizedTopic);

                        var publisherMsg = new Message();
                        publisherMsg.initMessage(publisherIdentifier, subscriberType, messageType, "Welcome " + subscriberType);
                        Console.WriteLine("Publisher sending message: {0}", publisherMsg.ToString());

                        publisherSocket.SendMoreFrame(messageType).SendFrame(publisherMsg.Serialize());

                    }

                    msgCount += 100;
                    Console.WriteLine("\n Received {0} messages", msgCount);

                    Console.WriteLine("\n --- Press Ctrl + C to exit ... --- \n");
                }

            }
        }
开发者ID:bbcCorp,项目名称:NetMQDemo,代码行数:45,代码来源:zmqPublisher.cs

示例4: PacketExecute

        private void PacketExecute(object state)
        {
            try
            {
                KeyValuePair<ServerConnection, Packet> order = (KeyValuePair<ServerConnection, Packet>)state;

                BinaryReader reader = new BinaryReader(order.Value.Request);
                Message msgRequest = Message.Deserialize(reader, (id) => StorageEngine.Find(id));

                IDescriptor clientDescription = msgRequest.Description;
                CommandCollection resultCommands = new CommandCollection(1);

                try
                {
                    var commands = msgRequest.Commands;

                    if (msgRequest.Description != null) // XTable commands
                    {
                        XTablePortable table = (XTablePortable)StorageEngine.OpenXTablePortable(clientDescription.Name, clientDescription.KeyDataType, clientDescription.RecordDataType);
                        table.Descriptor.Tag = clientDescription.Tag;

                        for (int i = 0; i < commands.Count - 1; i++)
                        {
                            ICommand command = msgRequest.Commands[i];
                            CommandsIIndexExecute[command.Code](table, command);
                        }

                        ICommand resultCommand = CommandsIIndexExecute[msgRequest.Commands[commands.Count - 1].Code](table, msgRequest.Commands[commands.Count - 1]);
                        if (resultCommand != null)
                            resultCommands.Add(resultCommand);

                        table.Flush();
                    }
                    else //Storage engine commands
                    {
                        ICommand command = msgRequest.Commands[commands.Count - 1];

                        var resultCommand = CommandsStorageEngineExecute[command.Code](command);

                        if (resultCommand != null)
                            resultCommands.Add(resultCommand);
                    }
                }
                catch (Exception e)
                {
                    resultCommands.Add(new ExceptionCommand(e.Message));
                }

                MemoryStream ms = new MemoryStream();
                BinaryWriter writer = new BinaryWriter(ms);

                Descriptor responseClientDescription = new Descriptor(-1, "", StructureType.RESERVED, DataType.Boolean, DataType.Boolean, null, null, DateTime.Now, DateTime.Now, DateTime.Now, null);

                Message msgResponse = new Message(msgRequest.Description == null ? responseClientDescription : msgRequest.Description, resultCommands);
                msgResponse.Serialize(writer);

                ms.Position = 0;
                order.Value.Response = ms;
                order.Key.PendingPackets.Add(order.Value);
            }
            catch (Exception exc)
            {
                TcpServer.LogError(exc);
            }
        }
开发者ID:ZhenghaiYe,项目名称:iveely,代码行数:65,代码来源:StorageEngineServer.cs

示例5: BroadcastToTheGroup

 private void BroadcastToTheGroup(Message pushMessage)
 {
     foreach (var client in _clients)
     {
         client.Value.Send(pushMessage.Serialize());
     }
 }
开发者ID:kevoree,项目名称:kevoree-dotnet-group-ws,代码行数:7,代码来源:WSGroupServerWSService.cs

示例6: MakeChunks

            /// <summary>
            /// Serializes the given message and constructs a number of
            /// chunks containing the serialized data.
            /// </summary>
            /// <param name="message">The message to serialize.</param>
            /// <param name="messageSequence">
            /// A reference to a counter which will be incremented.
            /// This becomes the value of each chunk's
            /// <see cref="Chunk.MessageSequence"/> field.
            /// </param>
            /// <returns>
            /// A non-empty array containing the created chunks.
            /// </returns>
            public Chunk[] MakeChunks(Message message, ref ulong messageSequence)
            {
                ++messageSequence;
                ulong currentChunkSequence = 0;
                ulong maxSize = this.m_MaximumChunkSize;

                using(MemoryStream stream = new MemoryStream()) {
                    // Serialize the message.
                #if GENERIC_SERIALIZATION
                    message.Serialize().WriteToStream( stream );
                #else
                    this.m_Formatter.Serialize( stream, message );
                #endif

                    // Calculate the number of chunks needed to span the message and allocate an array to hold them.
                    ulong length = ((ulong) stream.Length);
                    ulong count = (length / maxSize) + (length % maxSize == 0ul ? 0ul : 1ul);
                    Chunk[] chunks = new Chunk[count];

                    stream.Position = 0;
                    int index = 0;
                    for(ulong amountLeft; (amountLeft = length - ((ulong) stream.Position)) > 0; index++) {
                        // Read the deserialized data into a small array.
                        byte[] chunk = new byte[amountLeft < maxSize ? amountLeft : maxSize];
                        int read = stream.Read(chunk, 0, chunk.Length);
                        if(read != chunk.Length)
                            throw new ApplicationException("Couldn't read enough data from MemoryStream.");

                        // Create a chunk, updating the sequence numbers.
                        chunks[index] = new Chunk(chunk, messageSequence, currentChunkSequence++, count);
                    }

                    return chunks;
                }
            }
开发者ID:ClassroomPresenter,项目名称:CP3,代码行数:48,代码来源:Chunk.cs

示例7: SendFileList

 /// <summary>
 /// Creates a file list packet and sends it to the peer
 /// </summary>
 private void SendFileList()
 {
     AMessageData messageData = new FileListGetMessageData(_fileList);
     Message fileListMessage = new Message(new MessageHeader(ServiceTypes.FILE_LIST_GET), messageData);
     byte[] buffer = fileListMessage.Serialize();
     client.GetStream().Write(buffer, 0, buffer.Length);
 }
开发者ID:dceara,项目名称:ournaim,代码行数:10,代码来源:PeerConnectionHandler.cs

示例8: ProccessOutputs

        /// <summary>
        /// Writes packets to the receiver peer
        /// </summary>
        private void ProccessOutputs()
        {
            if (_cancelCurrentTransfer)
            {
                _cancelCurrentTransfer = false;
                currentFileStream.Close();
                currentFileStream = null;
                return;
            }
            if (currentFileStream == null)
                return;
            NetworkStream clientStream = client.GetStream();
            byte[] buffer = new byte[AMessageData.MAX_MESSAGE_SIZE];
            long nextPosition = currentFilePosition+AMessageData.MAX_MESSAGE_SIZE > currentFileStream.Length ?
                (currentFileStream.Length-currentFilePosition) : (currentFilePosition + AMessageData.MAX_MESSAGE_SIZE);
            currentFileStream.Lock(currentFilePosition, nextPosition);
            int readBytes = currentFileStream.Read(buffer, 0, AMessageData.MAX_MESSAGE_SIZE);
            currentFileStream.Lock(currentFilePosition, nextPosition);
            currentFilePosition = nextPosition;

            Message toSendMessage = new Message(new MessageHeader(ServiceTypes.FILE_TRANSFER_SEND),
                                                new FileTransferSendMessageData(currentFileId, (int)currentFileStream.Length, buffer));

            byte[] toSendBuffer = toSendMessage.Serialize();

            clientStream.Write(toSendBuffer, 0, toSendBuffer.Length);

            if(readBytes < AMessageData.MAX_MESSAGE_SIZE)
            {
                currentFileStream.Close();
                currentFileStream = null;
            }
        }
开发者ID:dceara,项目名称:ournaim,代码行数:36,代码来源:PeerConnectionHandler.cs

示例9: ReceiveFile

 /// <summary>
 /// This method is invoked to receive a file from the peer
 /// </summary>
 /// <param name="writeLocation">The location on the local disk where the file is saved</param>
 /// <param name="fileId">The id of the file to be transfered</param>
 private void ReceiveFile(string writeLocation, int fileId)
 {
     FileStream localFileStream = new FileStream(writeLocation, FileMode.OpenOrCreate);
     int receivedSize = 0;
     byte[] headerBuffer = new byte[MessageHeader.HEADER_SIZE];
     int readBytes = receiverStream.Read(headerBuffer, 0, MessageHeader.HEADER_SIZE);
     ushort contentLength = AMessageData.ToShort(headerBuffer[MessageHeader.HEADER_SIZE - 2], headerBuffer[MessageHeader.HEADER_SIZE - 1]);
     byte[] contentBuffer = new byte[contentLength];
     readBytes = receiverStream.Read(contentBuffer, 0, contentLength);
     byte[] rawData = new byte[headerBuffer.Length+contentLength];
     Array.Copy(headerBuffer,rawData,headerBuffer.Length);
     Array.Copy(contentBuffer,0,rawData,headerBuffer.Length,contentLength);
     Message receivedMessage = new Message(rawData);
     FileTransferSendMessageData messageData = (FileTransferSendMessageData)Message.GetMessageData(receivedMessage);
     localFileStream.Write(messageData.Content, 0, messageData.Content.Length);
     receivedSize += messageData.Content.Length;
     while (messageData.FileLength > receivedSize)
     {
         lock(this.toCancel)
         {
             if (this.toCancel.Value)
             {
                 this.toCancel.Value = false;
                 localFileStream.Close();
                 AMessageData cancelMessageData = new NackMessageData();
                 Message cancelMessage = new Message(new MessageHeader(ServiceTypes.NACK), cancelMessageData);
                 byte[] buffer = cancelMessage.Serialize();
                 receiverStream.Write(buffer, 0, buffer.Length);
                 File.Delete(writeLocation);
                 return;
             }
         }
         headerBuffer = new byte[MessageHeader.HEADER_SIZE];
         readBytes = receiverStream.Read(headerBuffer, 0, MessageHeader.HEADER_SIZE);
         contentLength = AMessageData.ToShort(headerBuffer[MessageHeader.HEADER_SIZE - 2], headerBuffer[MessageHeader.HEADER_SIZE - 1]);
         contentBuffer = new byte[contentLength];
         readBytes = receiverStream.Read(contentBuffer, 0, contentLength);
         rawData = new byte[headerBuffer.Length + contentLength];
         Array.Copy(headerBuffer, rawData, headerBuffer.Length);
         Array.Copy(contentBuffer, 0, rawData, headerBuffer.Length, contentLength);
         receivedMessage = new Message(rawData);
         messageData = (FileTransferSendMessageData)Message.GetMessageData(receivedMessage);
         localFileStream.Write(messageData.Content, 0, messageData.Content.Length);
     }
     localFileStream.Close();
 }
开发者ID:dceara,项目名称:ournaim,代码行数:51,代码来源:PeerConnectionHandler.cs

示例10: GetFileList

        /// <summary>
        /// This method is invoked to request the filelist from the peer
        /// </summary>
        /// <returns>The peer file list</returns>
        private IDictionary<int, string> GetFileList()
        {
            AMessageData messageData = new FileListGetMessageData(new Dictionary<int, string>());
            Message fileListGetMessage = new Message(new MessageHeader(ServiceTypes.FILE_LIST_GET), messageData);
            byte[] buffer = fileListGetMessage.Serialize();
            receiverStream.Write(buffer, 0, buffer.Length);

            byte[] headerBuffer = new byte[MessageHeader.HEADER_SIZE];
            int readBytes = receiverStream.Read(headerBuffer, 0, MessageHeader.HEADER_SIZE);
            if (readBytes < MessageHeader.HEADER_SIZE)
            {
            #warning must test this part!!!!!!!!
                receiverStream.Flush();
                return new Dictionary<int,string>();
            }
            ushort contentLength = AMessageData.ToShort(headerBuffer[MessageHeader.HEADER_SIZE - 2], headerBuffer[MessageHeader.HEADER_SIZE-1]);
            byte[] rawDataBuffer = new byte[headerBuffer.Length + contentLength];
            Array.Copy(headerBuffer, 0, rawDataBuffer, 0, headerBuffer.Length);
            readBytes = receiverStream.Read(rawDataBuffer, headerBuffer.Length, contentLength);
            if (readBytes != contentLength)
            {
            #warning must test this part!!!!!!!!
                receiverStream.Flush();
                return new Dictionary<int, string>();
            }
            Message receivedMessage = new Message(rawDataBuffer);
            if (receivedMessage.Header.ServiceType != ServiceTypes.FILE_LIST_GET)
            {
                return new Dictionary<int, string>();
            }
            FileListGetMessageData fileListMessageData = (FileListGetMessageData)Message.GetMessageData(receivedMessage);
            return fileListMessageData.FileList;
        }
开发者ID:dceara,项目名称:ournaim,代码行数:37,代码来源:PeerConnectionHandler.cs


注:本文中的Message.Serialize方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。