基本信息
源码名称:C# socket通讯 例子
源码大小:0.22M
文件格式:.7z
开发语言:C#
更新时间:2016-03-01
   友情提示:(无需注册或充值,赞助后即可获取资源下载链接)

     嘿,亲!知识可是无价之宝呢,但咱这精心整理的资料也耗费了不少心血呀。小小地破费一下,绝对物超所值哦!如有下载和支付问题,请联系我们QQ(微信同号):813200300

本次赞助数额为: 5 元 
   源码介绍



using System;
using System.Linq;
using System.Text;
using Helios.Net;

namespace HeliosChat.Common
{
    public class MessageConverter
    {
        public static Message ToMessage(NetworkData data)
        {
            try
            {
                var commandData = data.Buffer.Take(4).ToArray();
                var contentData = data.Buffer.Skip(4).Take(data.Buffer.Length - 4).ToArray();

                var command = BitConverter.ToInt32(commandData,0);
                var content = Encoding.UTF8.GetString(contentData);

                return new Message()
                {
                    Command = (Command)command,
                    Content = content
                };
            }
            catch (Exception exc)
            {
                Console.WriteLine("Cant convert NetworkData to Message : {0}", exc.Message);
            }

            return null;

        }

        public static byte[] ToBytes(Message message)
        {
            try
            {
                var commandBytes = BitConverter.GetBytes((int)message.Command);
                var messageBytes = Encoding.UTF8.GetBytes(message.Content);
                var bytes = new byte[commandBytes.Length   messageBytes.Length];
                commandBytes.CopyTo(bytes, 0);
                messageBytes.CopyTo(bytes, commandBytes.Length);

                return bytes;
            }
            catch (Exception exc)
            {
                Console.WriteLine("Cant convert message to bytes : {0}", exc.Message);
            }

            return null;
        }

    }
}