socket通信较完善方案,UMD手机电子书的读取和制作源码
分类:微服架构

最近一项目中要求显示网络流量,而且必须使用C#。

这段时间一直在学习C#, 以前一直搞网络的,还是从Ping程序的实现写起吧.
ping的调用方法如下:
Ping mPing=new Ping();
mPing.Pinging(“127.0.0.1“,255,65535);
mPing.Receive(); //成功接收返回true,timeout 返回false
全部源代码如下:
using System;
using System.IO;
using System.Net;
using System.Net.Sockets;
namespace Ping
{
///
/// Summary description for Ping.
///
///
//
//
//IP Header
public class IPHDR
{
public byte VIHL
{
get{return mVIHL;}
set{mVIHL=value;}
}private byte mVIHL;
public byte TOS
{
get{return mTOS;}
set{mTOS=value;}
}private byte mTOS;
public short TotLen
{
get{return mTotLen;}
set{mTotLen=value;}
}private short mTotLen;
public short ID
{
get{return mID;}
set{mID=value;}
}private short mID;
public short FlagOff
{
get{return mFlagOff;}
set{mFlagOff=value;}
}private short mFlagOff;
public byte TTL
{
get{return mTTL;}
set{mTTL=value;}
}private byte mTTL;
public byte Protocol
{
get{return mProtocol;}
set{mProtocol=value;}
}private byte mProtocol;
public ushort Checksum
{
get{return mChecksum;}
set{mChecksum = value;}
}private ushort mChecksum;
public ulong iaSrc
{
get{return miaSrc;}
set{miaSrc=value;}
}private ulong miaSrc;
public ulong iaDst
{
get{return miaDst;}
set{miaDst=value;}
}private ulong miaDst;

c#的socket通信应用.文件较多.附件为工程. 

转载本文章,请注明“来自角摩手机乐园(

事实上,调用 IpHlpApi.dll 的 GetIfTable API 可以轻易获得网络信息和网络流量。只是要在C#中实现还是比较复杂。

public static string Address(ulong obj)
{
byte s1=(byte)obj;
byte s2=(byte)(obj>>8);
byte s3=(byte)(obj>>16);
byte s4=(byte)(obj>>24);
return String.Format("{0}.{1}.{2}.{3}",s1,s2,s3,s4);//s1+"."+s2+"."+s3+"."+s4;
}
public void Encode(BinaryWriter writer)
{
writer.Write(VIHL);
writer.Write(TOS);
writer.Write((Int16)TotLen);
writer.Write((Int16)ID);
writer.Write((Int16)FlagOff);
writer.Write(TTL);
writer.Write(Protocol);
writer.Write((UInt16)Checksum);
writer.Write((UInt32)iaSrc);
writer.Write((UInt32)iaDst);

core

UMDBookWriter.cs

先看看怎么定义该 API
[DllImport("IpHlpApi.dll")]
        extern static public uint GetIfTable(byte[] pIfTable, ref uint pdwSize, bool bOrder);
本来想把 pIfTable 定义为 IntPtr,但是这样的结果是,获取的信息是错误的(直到现在都不知是什么原因)。

}
public void Decode(BinaryReader reader)
{
VIHL=reader.ReadByte();
TOS=reader.ReadByte();
TotLen=reader.ReadInt16();
ID=reader.ReadInt16();
FlagOff=reader.ReadInt16();
TTL=reader.ReadByte();
Protocol=reader.ReadByte();
Checksum=reader.ReadUInt16();
iaSrc=reader.ReadUInt32();
iaDst=reader.ReadUInt32();
}

  AbstractBytesWorker.cs    字节工作器(基类),用于用于同一不同功能的字节工作器 

namespace JoymoEnt.JoymoParse.umd
{
    using ICSharpCode.SharpZipLib.Zip.Compression;
    using System;
    using System.Collections;
    using System.Drawing;
    using System.Drawing.Imaging;
    using System.IO;
    using System.Reflection;
    using System.Runtime.InteropServices;
    using System.Text;

但显然定义为 byte[] 是不能直接使用的。幸好在 Google Code Search 找到了三个类:

}
//ICMP Header;
public class ICMPHDR
{
public byte Type
{
get{return mType;}
set{mType=value;}
}private byte mType;
public byte Code
{
get{return mCode;}
set{mCode=value;}
}private byte mCode=0;
public ushort Checksum
{
get{return mChecksum;}
set{mChecksum=value;}
}private ushort mChecksum=0;
public ushort ID
{
get{return mID;}
set{mID=value;}
}private ushort mID;
public ushort Seq
{
get{return mSeq;}
set{mSeq=value;}
}private ushort mSeq;
public ulong tmSend
{
get{return mtmSend;}
set{mtmSend=value;}
}private ulong mtmSend;

BinaryHand.cs  2进制处理器.  ThDispose.cs 处理回收相关

    public class UMDBookWriter/*
    {
        private CUMDBook _Book = null;
        private int[] _ChaptersOff = null;
        private Random _Random = new Random();
        private string _TotalContent = string.Empty;
        private int _TotalContentLen = 0;
        private ArrayList _TotalImageList = new ArrayList();
        private const int A_32K_BYTE = 0x8000;
        private const byte ACTUAL_WIDTH_S60_HORI = 0xcc;
        private const byte ACTUAL_WIDTH_S60_VERT = 0xac;
        private const byte ACTUAL_WIDTH_SP = 0xa6;
        private const uint BASE_REFN_CHAP_OFF = 0x3000;
        private const uint BASE_REFN_CHAP_STR = 0x4000;
        private const uint BASE_REFN_CONTENT = 0x2000;
        private const uint BASE_REFN_COVER = 0x1000;
        private const uint BASE_REFN_PAGE_OFFSET = 0x7000;
        private const string BEYOND_END_FLAG = ""0";
        private const int BYTE_LEN = 1;
        private const byte COVER_TYPE_BMP = 0;
        private const byte COVER_TYPE_GIF = 2;
        private const byte COVER_TYPE_JPG = 1;
        private const int CURR_VERSION = 1;
        private const short DCTS_CMD_ID_AUTHOR = 3;
        private const short DCTS_CMD_ID_CDS_KEY = 240;
        private const short DCTS_CMD_ID_CHAP_OFF = 0x83;
        private const short DCTS_CMD_ID_CHAP_STR = 0x84;
        private const short DCTS_CMD_ID_CONTENT_ID = 10;
        private const short DCTS_CMD_ID_COVER_PAGE = 130;
        private const short DCTS_CMD_ID_DAY = 6;
        private const short DCTS_CMD_ID_FILE_LENGTH = 11;
        private const short DCTS_CMD_ID_FIXED_LEN = 12;
        private const short DCTS_CMD_ID_GENDER = 7;
        private const short DCTS_CMD_ID_LICENSE_KEY = 0xf1;
        private const short DCTS_CMD_ID_MONTH = 5;
        private const short DCTS_CMD_ID_PAGE_OFFSET = 0x87;
        private const short DCTS_CMD_ID_PUBLISHER = 8;
        private const short DCTS_CMD_ID_REF_CONTENT = 0x81;
        private const short DCTS_CMD_ID_TITLE = 2;
        private const short DCTS_CMD_ID_VENDOR = 9;
        private const short DCTS_CMD_ID_VERSION = 1;
        private const short DCTS_CMD_ID_YEAR = 4;
        private const byte FIXED_LINE_PER_PAGE_S60 = 50;
        private const byte FIXED_LINE_PER_PAGE_SP = 0x19;
        private ArrayList widthData_S60 = new ArrayList();
        private ArrayList widthData_SP = new ArrayList();

CustomtMarshaler.cs
using System;
using System.IO;
using System.Collections;
using System.Reflection;
using System.Runtime.InteropServices;
using System.Threading;

public int nTaskId
{
get{return mnTaskId;}
set{mnTaskId=value;}
}private int mnTaskId;
public void Encode(BinaryWriter writer)
{
writer.Write(Type);
writer.Write(Code);
writer.Write((UInt16)Checksum);
writer.Write((UInt16)ID);
writer.Write((UInt16)Seq);
writer.Write((UInt32)tmSend);
writer.Write(nTaskId);
}
public void Decode(BinaryReader reader)
{
Type=reader.ReadByte();
Code=reader.ReadByte();
Checksum=reader.ReadUInt16();
ID=reader.ReadUInt16();
Seq=reader.ReadUInt16();
tmSend=reader.ReadUInt32();
nTaskId=reader.ReadInt32();
}
public uint Sum()
{
uint sum=0;
sum +=(ushort)(Type+(Code<<8));
sum +=(ushort)ID;
sum +=(ushort)Seq;
sum +=(ushort)tmSend;
sum +=(ushort)(tmSend>>16);
sum +=(ushort)nTaskId;
sum +=(ushort)(nTaskId>>16);
return sum;
}
}
public class ECHOREQUEST
{
private char[] mChar;
public ICMPHDR icmp=new ICMPHDR();
public ECHOREQUEST(int size,char nChar)
{
mChar=new Char[size];
for(int i=0;i mChar[i]=nChar;
}
public void Encode(BinaryWriter writer)
{
chksum();
icmp.Encode(writer);
writer.Write(mChar);
}
/* public void Decode(BinaryReader reader)
{
icmp.Decode(reader);
string s=reader.ReadString();
mChar=s.ToCharArray();
}
*/ private void chksum()
{
uint sum=icmp.Sum();
for(int i=0;i sum +=(ushort)(mChar[i]+(mChar[i+1]<<8));
//
sum = (sum >> 16) + (sum & 0xffff); // add hi 16 to low 16
sum += (sum >> 16); // add carry
short answer = (short)~sum; // truncate to 16 bits
icmp.Checksum=(ushort)answer;
}
}
//ICMP Echo Reply
public class ECHOREPLY
{
public IPHDR ipHdr=null;
public ICMPHDR icmpHdr=null;
public char[] cFiller;
public void Decode(BinaryReader reader)
{
ipHdr=new IPHDR();
ipHdr.Decode(reader);

  crc  
entity

        public UMDBookWriter(CUMDBook book)
        {
            this._Book = book;
        }

namespace Lemony.SystemInfo
{
   
    /**////
    /// CustomMarshaler class implementation.
    ///
    public abstract class CustomMarshaler
    {
        Fields#region Fields
        // The internal buffer
        internal byte[] data;
        private MemoryStream stream;
        private BinaryReader binReader;
        private BinaryWriter binWriter;
       
        #endregion
   
        constructors#region constructors

icmpHdr=new ICMPHDR();
icmpHdr.Decode(reader);

  ThPersonInfo.cs

        private byte CharWidth_S60(string @char, byte fontSize)
        {
            ushort num = @char[0];
            foreach (SWidthData data in this.widthData_S60)
            {
                if (((data.FontSize == fontSize) && (num >= data.rngFrom)) && (num <= data.rngTo))
                {
                    if (data.vCount == 1)
                    {
                        return data.Value[0];
                    }
                    return data.Value[num - data.rngFrom];
                }
            }
            return fontSize;
        }

        public CustomMarshaler()
        {

int bytes=(int)reader.BaseStream.Length;
// cFiller=reader.ReadChars(8);
cFiller=reader.ReadChars(bytes-36);
}
}
public class StateObject
{
public Socket workSocket = null; // Client socket.
public const int BufferSize = 256; // Size of receive buffer.
public byte[] buffer = new byte[BufferSize]; // Receive buffer.
// public StringBuilder sb = new StringBuilder();// Received data string.
}

  manager

        private void ClearTempVariables()
        {
            this._TotalContent = string.Empty;
            this._TotalContentLen = 0;
            this._ChaptersOff = null;
            if (this.widthData_S60 == null)
            {
                this.widthData_S60 = new ArrayList();
            }
            else
            {
                this.widthData_S60.Clear();
            }
            if (this.widthData_SP == null)
            {
                this.widthData_SP = new ArrayList();
            }
            else
            {
                this.widthData_SP.Clear();
            }
        }

        }
       
        #endregion

public class Ping
{
Socket socket=null;
int m_id;
uint m_taskid;
uint m_seq;
System.Threading.ManualResetEvent recvDone=null;
DateTime m_dtSend;
public Ping()
{
m_seq=0;
recvDone=new System.Threading.ManualResetEvent(false);
socket=new Socket(AddressFamily.InterNetwork,SocketType.Raw,ProtocolType.Icmp);
//
// TODO: Add constructor logic here
//
}
public bool Pinging(string addr,int id, uint taskid)
{
try
{
m_id=id;
m_taskid=taskid;
Byte[] byReq =FillEchoReq();

  ThSocketManager.cs  ThSocketManagerBusiness.cs

        private byte[][] CompressTxtContent(Encoding encoding, CChapterList chapters)
        {
            string s = string.Empty;
            int num = 0;
            ArrayList list = new ArrayList(chapters.Count);
            int[] numArray = new int[chapters.Count];
            for (int i = 0; i < chapters.Count; i++)
            {
                string str2 = chapters[i].Content.Replace(""r"n", ""u2029") + ""u2029";
                list.Add(str2);
                s = s + str2;
                numArray[i] = num;
                num += str2.Length * 2;
            }
            byte[] bytes = new byte[num];
            bytes = Encoding.Unicode.GetBytes(s);
            int num3 = 0;
            if ((num % 0x8000) == 0)
            {
                num3 = num / 0x8000;
            }
            else
            {
                num3 = (num / 0x8000) + 1;
            }
            byte[][] bufferArray = new byte[num3][];
            int index = 0;
            byte[] input = new byte[0x8000];
            int num5 = 0;
            for (int j = 0; j < bytes.Length; j++)
            {
                input[num5] = bytes[j];
                num5++;
                if ((num5 == 0x8000) || (j == (bytes.Length - 1)))
                {
                    byte[] output = new byte[0x8000];
                    Deflater deflater = new Deflater(Deflater.BEST_COMPRESSION, false);
                    if (deflater.IsNeedingInput)
                    {
                        deflater.SetInput(input, 0, input.Length);
                    }
                    deflater.Finish();
                    deflater.Deflate(output);
                    bufferArray[index] = new byte[deflater.TotalOut];
                    Deflater deflater2 = new Deflater(Deflater.BEST_COMPRESSION, false);
                    if (deflater2.IsNeedingInput)
                    {
                        deflater2.SetInput(input, 0, input.Length);
                    }
                    deflater2.Finish();
                    deflater2.Deflate(bufferArray[index]);
                    index++;
                    input = null;
                    input = new byte[0x8000];
                    num5 = 0;
                }
            }
            return bufferArray;
        }

        public methods#region public methods

//send to

所有的业务

        private bool GetPageOffsetS60(byte size, uint actualWidth, out uint[] result)
        {
            if ((size != 0x10) && (size != 12))
            {
                result = new uint[0];
                return false;
            }
            this.GetWidthData_S60();
            ArrayList pagesOff = new ArrayList();
            pagesOff.Add(0);
            while (((uint) pagesOff[pagesOff.Count - 1]) < this._TotalContent.Length)
            {
                this.ParseOnePage((uint) (pagesOff.Count - 1), size, actualWidth, ref pagesOff, 1);
            }
            result = new uint[pagesOff.Count];
            for (int i = 0; i < pagesOff.Count; i++)
            {
                result[i] = ((uint) pagesOff[i]) * 2;
            }
            return true;
        }

        public void Deserialize()
        {
            if (data != null)
            {
                if (binReader != null)
                {
                    binReader.Close();
                    stream.Close();
                }
                // Create a steam from byte array
                stream = new MemoryStream(data);
                binReader = new BinaryReader(stream, System.Text.Encoding.Unicode);
                ReadFromStream(binReader);
                binReader.Close();
            }

IPEndPoint lep = new IPEndPoint(IPAddress.Parse(addr), 0);

  request 

        private bool GetPageOffsetSP(byte size, uint actualWidth, out uint[] result)
        {
            if ((size < 6) || (size > 0x10))
            {
                result = new uint[0];
                return false;
            }
            ArrayList pagesOff = new ArrayList();
            pagesOff.Add(0);
            while (((uint) pagesOff[pagesOff.Count - 1]) < this._TotalContent.Length)
            {
                this.ParseOnePage((uint) (pagesOff.Count - 1), size, actualWidth, ref pagesOff, 5);
            }
            result = new uint[pagesOff.Count];
            for (int i = 0; i < pagesOff.Count; i++)
            {
                result[i] = ((uint) pagesOff[i]) * 2;
            }
            return true;
        }

        }

socket.SendTo(byReq,lep);
}
catch(Exception e)
{
Console.WriteLine("Send error:"+e.ToString());
return false;
}

RequestCode.cs  请求码 

        private void GetWidthData_S60()/*
        {
            if (this.widthData_S60.Count == 0)
            {
                for (int i = 0; i < 2; i++)
                {
                    string path = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location) + @""FontWidthData"S60CHS." + ((i == 0) ? "S16" : "S12") + ".wdt";
                    if (File.Exists(path))
                    {
                        FileStream input = new FileStream(path, FileMode.Open, FileAccess.Read);
                        BinaryReader reader = new BinaryReader(input);
                        while (reader.BaseStream.Position < reader.BaseStream.Length)
                        {
                            SWidthData data = new SWidthData();
                            data.FontSize = (i == 0) ? ((byte) 0x10) : ((byte) 12);
                            data.rngFrom = reader.ReadUInt16();
                            data.rngTo = reader.ReadUInt16();
                            data.vCount = reader.ReadUInt16();
                            data.Value = reader.ReadBytes((int) data.vCount);
                            this.widthData_S60.Add(data);
                        }
                        reader.Close();
                        input.Close();
                    }
                }
            }
        }

        public void Serialize()
        {
            if (data != null)
            {
                stream = new MemoryStream(data);
                binWriter = new BinaryWriter(stream, System.Text.Encoding.Unicode);
                WriteToStream(binWriter);
                binWriter.Close();
            }
        }

return true;
}
private Byte[] FillEchoReq()
{
m_seq++;
if(m_seq>1000)
m_seq=1;
ECHOREQUEST req=new ECHOREQUEST(8,'E');
req.icmp.Type=8;
req.icmp.Code=0;
req.icmp.ID=(ushort)m_id;
req.icmp.Seq=(ushort)m_seq;
req.icmp.nTaskId=(int)m_taskid;
m_dtSend=DateTime.Now;

ThProtocolReq.cs 请求逻辑 

        private void GetWidthData_SP()
        {
            if (this.widthData_SP.Count == 0)
            {
                for (int i = 6; i < 0x10; i++)
                {
                    string path = string.Concat(new object[] { Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), @""FontWidthData"sunfon.s", i, ".wdt" });
                    if (File.Exists(path))
                    {
                        FileStream input = new FileStream(path, FileMode.Open, FileAccess.Read);
                        BinaryReader reader = new BinaryReader(input);
                        while (reader.BaseStream.Position < reader.BaseStream.Length)
                        {
                            SWidthData data = new SWidthData();
                            data.FontSize = (byte) i;
                            data.rngFrom = reader.ReadUInt16();
                            data.rngTo = reader.ReadUInt16();
                            data.vCount = reader.ReadUInt16();
                            data.Value = reader.ReadBytes((int) data.vCount);
                            this.widthData_SP.Add(data);
                        }
                        reader.Close();
                        input.Close();
                    }
                }
            }
        }

        public int GetSize()
        {   
            int size = 0;

req.icmp.tmSend=(ulong)DateTime.Now.Ticks;
MemoryStream stream=new MemoryStream();
BinaryWriter writer=new BinaryWriter(stream);
req.Encode(writer);

ThReqBytesWorker.cs 请求相关的字节工作器

        public string MakeImageBook(BinaryWriter writer)/*
        {
            this.WriteChaptersOff(writer);
            this.WriteChapterTitles(writer);
            if (this._Book.BookType[1] == 2)
            {
                this.WriteChapterImageContent(writer, 14);
            }
            else if (this._Book.BookType[1] == 3)
            {
                this.WriteChapterImageContent(writer, 15);
            }
            if (this._Book.Cover != null)
            {
                this.WriteBookCover(writer);
            }
            writer.Write('#');
            writer.Write((short) 0xf1);
            writer.Write((byte) 0);
            writer.Write((byte) 0x15);
            writer.Write(Encoding.ASCII.GetBytes(""0"0"0"0"0"0"0"0"0"0"0"0"0"0"0"0"));
            return null;
        }

            FieldInfo[] fields = this.GetType().GetFields(BindingFlags.Public | BindingFlags.Instance);

int toReads=(int)stream.Length;
//get Byte array.
Byte[] byReq=stream.ToArray();

  response

        public string MakeTxtBook(BinaryWriter writer)
        {
            uint[] numArray;
            Encoding bookEncoding = this._Book.BookEncoding;
            writer.Write('#');
            writer.Write((short) 11);
            writer.Write((byte) 0);
            writer.Write((byte) 9);
            writer.Write(this._TotalContentLen);
            this.WriteChaptersOff(writer);
            this.WriteChapterTitles(writer);
            if (this._Book.BookType[0] == 1)
            {
                this.WriteChapterTxtContents(writer);
            }
            if (this._Book.Cover != null)
            {
                this.WriteBookCover(writer);
            }
            this.GetPageOffsetS60(0x10, 0xcc, out numArray);
            this.WritePageOffset(0x10, 0xd0, ref numArray, writer, 1);
            this.GetPageOffsetS60(0x10, 0xac, out numArray);
            this.WritePageOffset(0x10, 0xb0, ref numArray, writer, 1);
            this.GetPageOffsetS60(12, 0xcc, out numArray);
            this.WritePageOffset(12, 0xd0, ref numArray, writer, 1);
            this.GetPageOffsetS60(12, 0xac, out numArray);
            this.WritePageOffset(12, 0xb0, ref numArray, writer, 1);
            this.GetPageOffsetSP(10, 0xa6, out numArray);
            this.WritePageOffset(10, 0xa6, ref numArray, writer, 5);
            return null;
        }

            foreach (FieldInfo field in fields )
            {
                if (field.FieldType.IsArray)
                {
                    size += GetFieldSize(field);
                }
                else if (field.FieldType == typeof(string))
                {
                    size += GetFieldSize(field)*2;
                }
                else if (field.FieldType.IsPrimitive)
                {
                    size += Marshal.SizeOf(field.FieldType);
                }
            }

stream.Close();
return byReq;
}

  respLogic

        private void ParseOnePage(uint pageNumber, byte fontSize, uint screenWidth, ref ArrayList pagesOff, int PID)
        {
            if (pageNumber < pagesOff.Count)
            {
                uint num = (uint) pagesOff[(int) pageNumber];
                int num2 = 0;
                string str = string.Empty;
                ArrayList list = new ArrayList();
                byte num3 = (PID == 1) ? ((byte) 50) : ((byte) 0x19);
                for (byte i = 0; i < num3; i = (byte) (i + 1))
                {
                    str = string.Empty;
                    string str2 = string.Empty;
                    byte num5 = 0;
                Label_0053:
                    if (num < this._TotalContent.Length)
                    {
                        str2 = this._TotalContent.Substring((int) num, 1);
                    }
                    else
                    {
                        str2 = ""0";
                    }
                    switch (str2)
                    {
                        case ""t":
                        case ""0":
                            str2 = "銆€";
                            break;
                    }
                    byte num6 = this.CharWidth_S60(str2, fontSize);
                    if (str2 == ""u2029")
                    {
                        num6 = 0;
                    }
                    if ((num6 + num5) <= screenWidth)
                    {
                        num5 = (byte) (num5 + num6);
                        num++;
                        if (str2 != ""u2029")
                        {
                            str = str + str2;
                            goto Label_0053;
                        }
                    }
                    if (str2 != ""u2029")
                    {
                        list.Add(str.Length);
                    }
                    else
                    {
                        list.Add(str.Length + 1);
                    }
                    num2 += (int) list[i];
                    if (i == ((byte) (num3 - 1)))
                    {
                        if ((num < this._TotalContent.Length) && (num > ((uint) pagesOff[pagesOff.Count - 1])))
                        {
                            pagesOff.Add(((uint) num2) + ((uint) pagesOff[pagesOff.Count - 1]));
                        }
                        if (num >= this._TotalContent.Length)
                        {
                            pagesOff.Add((uint) this._TotalContent.Length);
                        }
                    }
                }
            }
        }

            return size;
        }

private static uint iocntlCheck(Socket s)
{

    ThProtocolResp.cs 处理服务器响应的数据.

        private string Precheck()
        {
            if ((this._Book.BookTitle == null) || (this._Book.BookTitle.Length < 1))
            {
                return "标题不能为空!";
            }
            if ((this._Book.Author == null) || (this._Book.Author.Length < 1))
            {
                return "作者不能为空!";
            }
            if ((this._Book.Chapters == null) || (this._Book.Chapters.Count < 1))
            {
                return "内容数量不能小于0!";
            }
            if ((this._Book.BookPath == null) || (this._Book.BookPath.Length < 1))
            {
                return "保存文件的路径不不正确!";
            }
            if (File.Exists(this._Book.BookPath))
            {
                File.Delete(this._Book.BookPath);
            }
            return null;
        }

        #endregion

// Set up the input and output byte arrays.
byte[] inValue = BitConverter.GetBytes(0);
byte[] outValue = BitConverter.GetBytes(0);

    ThProtocolRespDelegates.cs 所有的代理.用于通知客户的事件.

        private string Prepare()/*
        {
            string str = string.Empty;
            int[] numArray = new int[this._Book.Chapters.Count];
            int num = 0;
            CChapter chapter = null;
            string str2 = null;
            for (int i = 0; i < this._Book.Chapters.Count; i++)
            {
                chapter = this._Book.Chapters[i];
                numArray[i] = num;
                if (this._Book.BookType[1] == 2)
                {
                    this._TotalImageList.AddRange(chapter.ImageList);
                    num += chapter.ImageList.Count;
                }
                else if (this._Book.BookType[1] == 1)
                {
                    str2 = chapter.Content.Replace(""r"n", ""u2029") + ""u2029";
                    str = str + str2;
                    num += str2.Length * 2;
                }
            }
            this._TotalContent = str;
            this._TotalContentLen = num;
            this._ChaptersOff = numArray;
            return null;
        }

        properties#region properties

// Check how many bytes have been received.
s.IOControl(0x4004667F, inValue, outValue);
uint bytesAvail = BitConverter.ToUInt32(outValue, 0);
return bytesAvail;
}
//used to check reply data by sync
public bool checkReply()
{
uint byAvail=iocntlCheck(socket);
if(byAvail<=0)
return false;
try
{
Byte[] recv=new Byte[byAvail];
socket.Receive(recv);
return checkEchoReply(recv,(int)byAvail);
}
catch(Exception e)
{
Console.WriteLine(e.ToString());
return false;
}
}
//Directly analyze the byte array.

    ThProtocolRespEvents.cs 所有的事件.用于调用客户的. 

        public string Write()
        {
            string message = this.Precheck();
            if (message == null)
            {
                this.ClearTempVariables();
                message = this.Prepare();
                if (message != null)
                {
                    return message;
                }
                BinaryWriter writer = null;
                FileStream output = new FileStream(this._Book.BookPath, FileMode.OpenOrCreate, FileAccess.Write);
                try
                {
                    writer = new BinaryWriter(output);
                    short num = (short) (this._Random.Next(0x401, 0x7fff) % 0xffff);
                    writer.Write((uint) 0xde9a9b89);
                    writer.Write('#');
                    writer.Write((short) 1);
                    writer.Write((byte) 0);
                    writer.Write((byte) 8);
                    writer.Write(this._Book.BookType[1]);
                    writer.Write(num);
                    this.WriteBookProperties(writer);
                    if (this._Book.BookType[1] == 1)
                    {
                        this.MakeTxtBook(writer);
                    }
                    else if (this._Book.BookType[1] == 2)
                    {
                        this.MakeImageBook(writer);
                    }
                    writer.Write('#');
                    writer.Write((short) 12);
                    writer.Write((byte) 1);
                    writer.Write((byte) 9);
                    writer.Write((uint) (((uint) writer.BaseStream.Position) + 4));
                }
                catch (Exception exception)
                {
                    message = exception.Message;
                }
                finally
                {
                    if (writer != null)
                    {
                        writer.Close();
                        writer = null;
                    }
                    output.Close();
                    output = null;
                }
            }
            return message;
        }

        public byte[] ByteArray
        {
            get
            {
                return data;
            }
        }

public bool checkEchoReply1(Byte[] recv,int len)
{
if(len<36)
return false;
int ttl=recv[8];
string src=recv[12]+"."+recv[13]+"."+recv[14]+"."+recv[15];
string dst=recv[16]+"."+recv[17]+"."+recv[18]+"."+recv[19];
int type=recv[20];
if(type !=0)
return false;
//24,25, id
int id=recv[24]+(recv[25]<<8);
if(id !=m_id)
return false;
//26,27, seq
int seq=recv[26]+(recv[27]<<8);
//32,33,34,35, task id
int taskid=recv[32]+(recv[33]<<8)+(recv[34]<<16)+(recv[35]<<24);
if(taskid !=m_taskid)
return false;
int bytes= len-36;

  ThProtocolRespListeners.cs 所有的监听器,用于控制事件如何订阅

        private void WriteBookCover(BinaryWriter Writer)
        {
            uint num = (uint) (0x1000 + this._Random.Next(0xfff));
            byte[] buffer = null;
            MemoryStream stream = new MemoryStream();
            this._Book.Cover.Save(stream, ImageFormat.Gif);
            stream.Seek(0L, SeekOrigin.Begin);
            buffer = new byte[stream.Length];
            stream.Read(buffer, 0, buffer.Length);
            stream.Close();
            stream = null;
            Writer.Write('#');
            Writer.Write((short) 130);
            Writer.Write((byte) 1);
            Writer.Write((byte) 10);
            Writer.Write((byte) 1);
            Writer.Write(num);
            Writer.Write('$');
            Writer.Write(num);
            Writer.Write((uint) (9 + buffer.Length));
            Writer.Write(buffer);
            buffer = null;
        }

        #endregion

TimeSpan ts=DateTime.Now-m_dtSend;
Console.WriteLine("Reply from {0}: bytes={1},icmp_seq={2},TTL={3},time={4} ms",
src,bytes,seq,ttl ,ts.Milliseconds );

    ThProtocolRespLogic.cs 处理服务器的数据 

        private void WriteBookProperties(BinaryWriter Writer)
        {
            Encoding bookEncoding = this._Book.BookEncoding;
            string propertyValue = this._Book.PublishDate.Year.ToString();
            string str2 = this._Book.PublishDate.Month.ToString();
            string str3 = this._Book.PublishDate.Day.ToString();
            this.WriteBookProperty(Writer, this._Book.BookTitle, 2);
            this.WriteBookProperty(Writer, this._Book.Author, 3);
            this.WriteBookProperty(Writer, propertyValue, 4);
            this.WriteBookProperty(Writer, str2, 5);
            this.WriteBookProperty(Writer, str3, 6);
            if ((this._Book.BookKind != null) && (this._Book.BookKind.Length > 0))
            {
                this.WriteBookProperty(Writer, this._Book.BookKind, 7);
            }
            if ((this._Book.Publisher != null) && (this._Book.Publisher.Length > 0))
            {
                this.WriteBookProperty(Writer, this._Book.Publisher, 8);
            }
            if ((this._Book.Vendor != null) && (this._Book.Vendor.Length > 0))
            {
                this.WriteBookProperty(Writer, this._Book.Vendor, 9);
            }
        }

        virtual and protected methods#region virtual and protected methods

return true;

  ThRespBytesWorker.cs 响应字节处理器

        private void WriteBookProperty(BinaryWriter Writer, string PropertyValue, int Type)
        {
            Writer.Write('#');
            Writer.Write((short) Type);
            Writer.Write((byte) 0);
            Writer.Write((byte) (5 + (PropertyValue.Length * 2)));
            Writer.Write(this._Book.BookEncoding.GetBytes(PropertyValue));
        }

        public virtual void ReadFromStream(BinaryReader reader)
        {
            object[] param = null;

}
//use IPHDR, ICMPHDR to analyze replyk data.
public bool checkEchoReply(Byte[] recv,int len)
{
//20bytes ip pack.
if(len<36)
return false;
MemoryStream stream=new MemoryStream(recv,0,len,false);
BinaryReader reader=new BinaryReader(stream);
ECHOREPLY reply=new ECHOREPLY();
reply.Decode(reader);

  BinaryMessageHandler.cs 处理数据包粘结,包一次数据不足等情况. 

        private void WriteChapterImageContent(BinaryWriter writer, int SegType)
        {
            int num = this._Random.Next(0x5f5e101, 0x3b9aca00);
            uint[] numArray = new uint[this._TotalImageList.Count];
            uint num2 = 0;
            if (this._TotalImageList.Count > 1)
            {
                num2 = (uint) this._Random.Next(0, this._TotalImageList.Count - 1);
            }
            writer.Write('#');
            writer.Write((short) SegType);
            writer.Write((byte) 0);
            writer.Write((byte) 6);
            writer.Write((byte) 1);
            byte[] buffer = null;
            for (int i = 0; i < this._TotalImageList.Count; i++)
            {
                Image image = (Image) this._TotalImageList[i];
                MemoryStream stream = new MemoryStream();
                image.Save(stream, ImageFormat.Jpeg);
                stream.Seek(0L, SeekOrigin.Begin);
                buffer = new byte[stream.Length];
                stream.Read(buffer, 0, buffer.Length);
                stream.Close();
                stream = null;
                numArray[i] = (uint) (this._Random.Next(1, 0xfffffff) * -1);
                writer.Write('$');
                writer.Write(numArray[i]);
                writer.Write((uint) (9 + buffer.Length));
                writer.Write(buffer);
                if (num2 == i)
                {
                    writer.Write('#');
                    writer.Write((short) 10);
                    writer.Write((byte) 0);
                    writer.Write((byte) 9);
                    writer.Write(num);
                }
            }
            num2 = (uint) (0x2000 + this._Random.Next(0xfff));
            writer.Write('#');
            writer.Write((short) 0x81);
            writer.Write((byte) 1);
            writer.Write((byte) 9);
            writer.Write(num2);
            writer.Write('$');
            writer.Write(num2);
            writer.Write((uint) (9 + (numArray.Length * 4)));
            for (int j = 0; j < numArray.Length; j++)
            {
                writer.Write(numArray[j]);
            }
        }

            // Get all public fields
            FieldInfo[] fields = this.GetType().GetFields(BindingFlags.Public | BindingFlags.Instance);
           
            // Loop through the fields
            foreach(FieldInfo field in fields)
            {
                // Retrieve the read method from ReadMethods hashtable
                MethodInfo method = (MethodInfo)MarshallingMethods.ReadMethods[field.FieldType];

stream.Close();
string dst,src;
dst=IPHDR.Address(reply.ipHdr.iaDst);
src=IPHDR.Address(reply.ipHdr.iaSrc);

ResponseCode.cs 响应码

        private void WriteChaptersOff(BinaryWriter writer)/*
        {
            uint num = (uint) (0x3000 + this._Random.Next(0xfff));
            writer.Write('#');
            writer.Write((short) 0x83);
            writer.Write((byte) 1);
            writer.Write((byte) 9);
            writer.Write(num);
            writer.Write('$');
            writer.Write(num);
            writer.Write((uint) (9 + (this._ChaptersOff.Length * 4)));
            for (int i = 0; i < this._ChaptersOff.Length; i++)
            {
                writer.Write(this._ChaptersOff[i]);
            }
        }

                if (field.FieldType.IsArray)
                {
                    Type element = field.FieldType.GetElementType();
                    if (element.IsValueType && element.IsPrimitive)
                    {
                        if ((element == typeof(char)) || element == typeof(byte))
                        {                                                                                
                            param = new object[1];
                            param[0] = GetFieldSize(field);
                            field.SetValue(this, method.Invoke(reader, param));
                        }
                        else // any other value type array
                        {
                            param = new object[2];
                            param[0] = reader;
                            param[1] = GetFieldSize(field);
                            field.SetValue(this, method.Invoke(null, param));
                        }
                    }
                    else // array of sub structures
                    {
                        int size = GetFieldSize(field);
                        method = (MethodInfo)MarshallingMethods.ReadMethods[typeof(CustomMarshaler)];
                        Array objArray = Array.CreateInstance(element, size);
                        for(int i=0;i                        {
                            objArray.SetValue(Activator.CreateInstance(element), i);
                            method.Invoke(objArray.GetValue(i), new object[]{reader});
                        }
                        field.SetValue(this, objArray);
                    }
                }
                else if (field.FieldType == typeof(string))
                {   
                    param = new object[2];
                    param[0] = reader;
                    param[1] = GetFieldSize(field);
                    field.SetValue(this, method.Invoke(null, param));
                }
                else if (field.FieldType.IsValueType && field.FieldType.IsPrimitive)// regular value type
                {
                    field.SetValue(this, method.Invoke(reader, null));
                }
                else //process substructure
                {
                    CustomMarshaler subStruct = (CustomMarshaler)Activator.CreateInstance(field.FieldType);
                    subStruct.ReadFromStream(reader);
                }
            }
        }

//type
byte type=reply.icmpHdr.Type;
//24,25 id
int id=reply.icmpHdr.ID;
//26,27,seq
int seq=reply.icmpHdr.Seq ;
//

  socket

        private void WriteChapterTitles(BinaryWriter Writer)
        {
            uint num = (uint) (0x4000 + this._Random.Next(0xfff));
            int num2 = 0;
            foreach (CChapter chapter in this._Book.Chapters)
            {
                num2 += (chapter.Title.Length * 2) + 1;
            }
            Writer.Write('#');
            Writer.Write((short) 0x84);
            Writer.Write((byte) 1);
            Writer.Write((byte) 9);
            Writer.Write(num);
            Writer.Write('$');
            Writer.Write(num);
            Writer.Write((uint) (9 + num2));
            foreach (CChapter chapter2 in this._Book.Chapters)
            {
                Writer.Write((byte) (chapter2.Title.Length * 2));
                Writer.Write(this._Book.BookEncoding.GetBytes(chapter2.Title));
            }
        }

        public virtual void WriteToStream(BinaryWriter writer)
        {
            object[] param = null;

int bytes= len-36;

  TAsyncTcpClient.cs tcpClient类,read异步.

        private void WriteChapterTxtContents(BinaryWriter Writer)
        {
            Random random = new Random();
            int num2 = random.Next(0x5f5e101, 0x3b9aca00);
            byte[][] bufferArray = this.CompressTxtContent(this._Book.BookEncoding, this._Book.Chapters);
            int num3 = 0;
            int num4 = 0;
            if (bufferArray.Length > 1)
            {
                num3 = random.Next(0, bufferArray.Length - 1);
                num4 = random.Next(0, bufferArray.Length - 1);
            }
            uint[] numArray = new uint[bufferArray.Length];
            for (int i = 0; i < bufferArray.Length; i++)
            {
                numArray[i] = (uint) (random.Next(1, 0xfffffff) * -1);
                Writer.Write('$');
                Writer.Write(numArray[i]);
                Writer.Write((uint) (9 + bufferArray[i].Length));
                Writer.Write(bufferArray[i]);
                if (i == num3)
                {
                    Writer.Write('#');
                    Writer.Write((short) 0xf1);
                    Writer.Write((byte) 0);
                    Writer.Write((byte) 0x15);
                    Writer.Write(Encoding.ASCII.GetBytes(""0"0"0"0"0"0"0"0"0"0"0"0"0"0"0"0"));
                }
                if (i == num4)
                {
                    Writer.Write('#');
                    Writer.Write((short) 10);
                    Writer.Write((byte) 0);
                    Writer.Write((byte) 9);
                    Writer.Write(num2);
                }
            }
            uint num = (uint) (0x2000 + random.Next(0xfff));/*手机电子书*/
            Writer.Write('#');
            Writer.Write((short) 0x81);
            Writer.Write((byte) 1);
            Writer.Write((byte) 9);
            Writer.Write(num);
            Writer.Write('$');
            Writer.Write(num);
            Writer.Write((uint) (9 + (numArray.Length * 4)));
            for (int j = 0; j < numArray.Length; j++)
            {
                Writer.Write(numArray[j]);
            }
        }

            FieldInfo[] fields = this.GetType().GetFields(BindingFlags.Public | BindingFlags.Instance);
           
            foreach(FieldInfo field in fields)
            {
                // Check if we have any value
                object value = field.GetValue(this);
               
                MethodInfo method = (MethodInfo)MarshallingMethods.WriteMethods[field.FieldType];
               
                if (field.FieldType.IsArray)
                {
                    Type element = field.FieldType.GetElementType();
                    if (element.IsValueType && element.IsPrimitive)
                    {
                        //method.Invoke(writer, new object[] {value});
                        Array arrObject = (Array)field.GetValue(this);
                        param = new object[2];
                        param[0] = writer;
                        param[1] = arrObject;
                        method.Invoke(null, param);
                    }
                    else
                    {
                        //Get field size
                        int size = GetFieldSize(field);
                        //Get WriteToStream method
                        method = (MethodInfo)MarshallingMethods.WriteMethods[typeof(CustomMarshaler)];
                        Array arrObject = (Array)field.GetValue(this);
                        for(int i=0;i                        {
                            method.Invoke(arrObject.GetValue(i), new object[]{writer});
                        }
                    }                   
                }
                else if (field.FieldType == typeof(string))
                {   
                    param = new object[3];
                    param[0] = writer;
                    param[1] = field.GetValue(this);
                    param[2] = GetFieldSize(field);
                    method.Invoke(null, param);                    

//32,33,34,35, task id
DateTime dt=new DateTime((long)reply.icmpHdr.tmSend);
// Consdt.ToString();
uint taskid=(uint)reply.icmpHdr.nTaskId;//(uint)(recv[32]+(recv[33]<<8)+(recv[34]<<16)+(recv[35]<<24));
TimeSpan ts=DateTime.Now -m_dtSend;//dt;
if(type == 0 && id == m_id && m_taskid==taskid)
{
Console.WriteLine("Reply from {0}: bytes={1},icmp_seq={2},TTL={3},time={4} ms",
src,bytes,seq,reply.ipHdr.TTL ,ts.Milliseconds );

  testcase 

        private void WritePageOffset(byte fontSize, byte screenWidth, ref uint[] data, BinaryWriter writer, byte PID)
        {
            Random random = new Random();
            uint num = (uint) (0x7000 + random.Next(0xfff));
            writer.Write('#');
            writer.Write((short) 0x87);
            writer.Write(PID);
            writer.Write((byte) 11);
            writer.Write(fontSize);
            writer.Write(screenWidth);
            writer.Write(num);
            writer.Write('$');
            writer.Write(num);
            writer.Write((uint) (9 + (data.Length * 4)));
            foreach (uint num2 in data)
            {
                writer.Write(num2);
            }
        }

                }
                else if (field.FieldType.IsValueType && field.FieldType.IsPrimitive)// regular value type
                {
                    method.Invoke(writer, new object[] {value});
                }
            }
        }

return true;
}
else
{
// Console.WriteLine("Unknown data,{0},{1},type={2},icmp_seq={3}",
// src,dst,type,seq);
}
return false;

===============================================================

        [StructLayout(LayoutKind.Sequential)]
        private struct SWidthData
        {
            public byte FontSize;
            public ushort rngFrom;
            public ushort rngTo;
            public uint vCount;
            public byte[] Value;
        }
    }
}

        protected int GetFieldSize(FieldInfo field)
        {
            int size = 0;
            CustomMarshalAsAttribute attrib = (CustomMarshalAsAttribute)field.GetCustomAttributes(typeof(CustomMarshalAsAttribute), true)[0];
           
            if (attrib != null)
            {
                if (attrib.SizeField != null)
                {
                    FieldInfo sizeField = this.GetType().GetField(attrib.SizeField);
                    size = (int)sizeField.GetValue(this);
                }
                else
                {
                    size = attrib.SizeConst;   
                }
            }

}
public bool Receive()
{
try
{
recvDone.Reset();
StateObject so=new StateObject();
so.workSocket=socket;

  部分类代码:  BinaryMessageHandler 

UMDFactory.cs

            return size;
        }

// socket.SetSocketOption(SocketOptionLevel.Socket,SocketOptionName.ReceiveTimeout,5000);

C#代码 

namespace JoymoEnt.JoymoParse.umd
{
    using System;

        #endregion

IPEndPoint sender = new IPEndPoint(IPAddress.Any, 0);
EndPoint tempRemoteEP = (EndPoint)sender;

 图片 1)

    public class UMDFactory
    {
        private UMDFactory()
        {
        }

        helper methods#region helper methods

socket.BeginReceiveFrom(so.buffer,0,StateObject.BufferSize,0,ref tempRemoteEP,new AsyncCallback(receiveCallBack),so);

  1. #pragma warning disable 0219  
  2. using System;  
  3. using System.Collections.Generic;  
  4. using System.Linq;  
  5. using System.Text;  
  6. using System.IO;  
  7.   
  8. /// <summary>  
  9. /// 字节接收处理,粘包问题  
  10. /// </summary>  
  11. class BinaryMessageHandler : ThDispose  
  12. {  
  13.     List<byte> bytesList = new List<byte>();  
  14.   
  15.     private TAsyncTcpClient tcpClient;  
  16.   
  17.     public BinaryMessageHandler(TAsyncTcpClient tcpClient)  
  18.     {  
  19.         this.tcpClient = tcpClient;  
  20.     }  
  21.     public BinaryMessageHandler()  
  22.     {  
  23.   
  24.     }  
  25.   
  26.     override public void SelfDispose()  
  27.     {  
  28.         tcpClient = null;  
  29.         bytesList = null;  
  30.     }  
  31.       
  32.     /// <summary>  
  33.     /// 累积 字节.  
  34.     /// 每次累积后,测试是否有完整的包.  
  35.     /// </summary>  
  36.     /// <param name="buf"></param>  
  37.     public void Write(byte[] buf)  
  38.     {  
  39.         if (buf.Length > 0)  
  40.         {  
  41.             //累积字节  
  42.             bytesList.AddRange(buf);  
  43.             byte[] bytes = bytesList.ToArray<byte>();  
  44.             MemoryStream ms = new MemoryStream(bytes);  
  45.             BinaryReader reader = new BinaryReader(ms);  
  46.   
  47.             int header = reader.ReadUInt16();  
  48.             if (header == ThSocketManager.TH_HEADER)  
  49.             {  
  50.                 int len = reader.ReadUInt16();  
  51.                 int remainLen = len - 4;  
  52.                 if ((ms.Length - ms.Position) >= remainLen)  
  53.                 {  
  54.                     //有完整的数据包  
  55.                     ms.Position = 0;  
  56.                     byte[] pack = reader.ReadBytes(len);  
  57.   
  58.                     ReadPackage(pack);  
  59.                     //移除读完的数据包  
  60.                     bytesList.RemoveRange(0, len);  
  61.                 }  
  62.             }  
  63.             reader.Close();  
  64.             ms.Close();  
  65.         }  
  66.   
  67.     }  
  68.   
  69.     /// <summary>  
  70.     /// 读取服务端响应信息.  
  71.     /// </summary>  
  72.     /// <param name="bytes"></param>  
  73.     /// <returns></returns>  
  74.     public void ReadPackage(byte[] bytes)  
  75.     {  
  76.         //处理包头  
  77.         MemoryStream ms = new MemoryStream(bytes);  
  78.         ms.Position = 0;  
  79.         BinaryReader reader = new BinaryReader(ms, Encoding.UTF8);  
  80.         ushort header = reader.ReadUInt16();  
  81.         ushort totalLen = reader.ReadUInt16();  
  82.         ushort respCode = reader.ReadUInt16();  
  83.         short signature = reader.ReadInt16();  
  84.         int dataLen = totalLen - ThSocketManager.PREFIX_LENGTH;  
  85.         byte[] dataBytes = reader.ReadBytes(dataLen);  
  86.         reader.Close();  
  87.         ms.Close();  
  88.   
  89.         //调用服务端响应,包体处理器.  
  90.         tcpClient.thProtocolResp.ResponseHandler(respCode, dataBytes);  
  91.     }  
  92. }  

        public static CUMDBook CreateNewUMDBook()
        {
            return new CUMDBook();
        }

        private static bool CompareByteArrays (byte[] data1, byte[] data2)
        {
            // If both are null, they're equal
            if (data1==null && data2==null)
            {
                return true;
            }
            // If either but not both are null, they're not equal
            if (data1==null || data2==null)
            {
                return false;
            }
            if (data1.Length != data2.Length)
            {
                return false;
            }
            for (int i=0; i < data1.Length; i++)
            {
                if (data1[i] != data2[i])
                {
                    return false;
                }
            }
            return true;
        }

if(!recvDone.WaitOne())//.WaitOne(1000,false))
{//receive timeout
Console.WriteLine("Request timed out");
return false;
}

BinaryHand 

        public static CUMDBook ReadUMDBook(string filepath)
        {
            UMDBookReader reader = new UMDBookReader();
            return reader.Read(filepath);
        }

        #endregion

}
catch(Exception e)
{
Console.WriteLine("Fail,{0}",e.ToString());
return false;
}
return true;
}
public void receiveCallBack(IAsyncResult ar)
{
try
{
StateObject obj=(StateObject)ar.AsyncState;
Socket sock=obj.workSocket;
IPEndPoint ep=new IPEndPoint(IPAddress.Any,0);
EndPoint tempEP=(EndPoint)ep;
int recvs=sock.EndReceiveFrom(ar,ref tempEP);
if(checkEchoReply(obj.buffer,recvs))
recvDone.Set();
else
sock.BeginReceiveFrom(obj.buffer,0,StateObject.BufferSize,0,ref tempEP,new AsyncCallback(receiveCallBack),obj);
// Console.WriteLine("Address:{0}",((IPEndPoint)tempEP).Address);
}
catch(Exception e)
{
Console.WriteLine("CallBack Error:"+e.ToString());

C#代码 

        public static string WriteUMDBook(CUMDBook book)
        {
            UMDBookWriter writer = new UMDBookWriter(book);
            return writer.Write();
        }
    }
}

    }

}
}
public void clear()
{
socket.Close();
}
}
}

 图片 2)

 

    MarshallingMethods class#region MarshallingMethods class
    /**////
    /// MarshallingMethods class implementation.
    ///
    public class MarshallingMethods
    {
        public static Hashtable ReadMethods = new Hashtable();
        public static Hashtable WriteMethods = new Hashtable();
       
        constructors#region constructors

  1. #pragma warning disable 0219  
  2. using System.Text;  
  3. using System.IO;  
  4.   
  5. class BinaryHand  
  6. {  
  7.     /// <summary>  
  8.     /// 准备将数据发送至服务端  
  9.     /// </summary>  
  10.     /// <param name="clientId"></param>  
  11.     /// <param name="data"></param>  
  12.     /// <returns></returns>  
  13.     public static byte[] ToBytes(ushort requestCode, uint clientId, byte[] dataBytes)  
  14.     {  
  15.         MemoryStream ms = new MemoryStream();  
  16.         BinaryWriter writer = new BinaryWriter(ms);  
  17.         //2 ushort header  
  18.         writer.Write(ThSocketManager.TH_HEADER);  
  19.         //2 ushort total length  
  20.         ushort packageLen = ThSocketManager.PREFIX_LENGTH;  
  21.         if (dataBytes != null)  
  22.         {  
  23.             packageLen += (ushort)dataBytes.Length;  
  24.         }  
  25.         writer.Write(packageLen);  
  26.         //2 ushort protocol id  
  27.         writer.Write(requestCode);  
  28.         //2 short signature  
  29.         writer.Write((short)0);  
  30.         //4 unit client id  
  31.         //writer.Write(clientId);  
  32.         //x string data  
  33.         if (dataBytes != null)  
  34.             writer.Write(dataBytes);  
  35.         //计算crc,并写入[6,7]位置.  
  36.         byte[] tmpBytes = ms.ToArray();  
  37.         short signature = CRC16.Compute(tmpBytes);  
  38.         long oldPos = ms.Position;  
  39.         ms.Position = 6;  
  40.         writer.Write(signature);  
  41.         ms.Position = oldPos;  
  42.         //准备输出  
  43.         byte[] bytes = ms.ToArray();  
  44.   
  45.         writer.Close();  
  46.         ms.Close();  
  47.         return bytes;  
  48.     }  
  49.   
  50.     public static byte[] ToBytes(RequestCode requestCode, uint clientId, byte[] dataBytes)  
  51.     {  
  52.         return ToBytes((ushort)requestCode, clientId, dataBytes);  
  53.     }  
  54.   
  55.     public byte[] ToBytes(uint clientId, string data)  
  56.     {  
  57.         byte[] dataBytes = Encoding.UTF8.GetBytes(data);  
  58.         return ToBytes(RequestCode.None, clientId, dataBytes);  
  59.     }  
  60.   
  61.     /// <summary>  
  62.     /// 读取服务端响应信息.  
  63.     /// </summary>  
  64.     /// <param name="bytes"></param>  
  65.     /// <returns></returns>  
  66.     public byte[] FromBytes(byte[] bytes)  
  67.     {  
  68.         MemoryStream ms = new MemoryStream(bytes);  
  69.         ms.Position = 0;  
  70.         BinaryReader reader = new BinaryReader(ms, Encoding.UTF8);  
  71.         ushort header = reader.ReadUInt16();  
  72.         ushort totalLen = reader.ReadUInt16();  
  73.         ushort protocolId = reader.ReadUInt16();  
  74.         short signature = reader.ReadInt16();  
  75.         uint clientId = reader.ReadUInt32();  
  76.         int dataLen = totalLen - ThSocketManager.PREFIX_LENGTH;  
  77.         byte[] dataBytes = reader.ReadBytes(dataLen);  
  78.   
  79.         reader.Close();  
  80.         ms.Close();  
  81.         return dataBytes;  
  82.     }  
  83. }  

        static MarshallingMethods()
        {
            // Read Methods
            ReadMethods.Add(typeof(bool), typeof(BinaryReader).GetMethod("ReadBoolean"));
            ReadMethods.Add(typeof(byte), typeof(BinaryReader).GetMethod("ReadByte"));
            ReadMethods.Add(typeof(System.SByte), typeof(BinaryReader).GetMethod("ReadSByte"));
            ReadMethods.Add(typeof(System.Single), typeof(BinaryReader).GetMethod("ReadSingle"));
            ReadMethods.Add(typeof(byte[]), typeof(BinaryReader).GetMethod("ReadBytes"));
            ReadMethods.Add(typeof(char[]), typeof(BinaryReader).GetMethod("ReadChars"));
            ReadMethods.Add(typeof(System.Int16), typeof(BinaryReader).GetMethod("ReadInt16"));
            ReadMethods.Add(typeof(System.Int32), typeof(BinaryReader).GetMethod("ReadInt32"));
            ReadMethods.Add(typeof(System.UInt16), typeof(BinaryReader).GetMethod("ReadUInt16"));
            ReadMethods.Add(typeof(System.UInt32), typeof(BinaryReader).GetMethod("ReadUInt32"));
            ReadMethods.Add(typeof(System.String), typeof(MarshallingMethods).GetMethod("ReadString"));
            ReadMethods.Add(typeof(System.DateTime), typeof(MarshallingMethods).GetMethod("ReadDateTime"));
            ReadMethods.Add(typeof(System.Int16[]), typeof(MarshallingMethods).GetMethod("ReadInt16Array"));
            ReadMethods.Add(typeof(System.Int32[]), typeof(MarshallingMethods).GetMethod("ReadInt32Array"));
            ReadMethods.Add(typeof(System.UInt16[]), typeof(MarshallingMethods).GetMethod("ReadUInt16Array"));
            ReadMethods.Add(typeof(System.UInt32[]), typeof(MarshallingMethods).GetMethod("ReadUInt32Array"));
            ReadMethods.Add(typeof(CustomMarshaler), typeof(CustomMarshaler).GetMethod("ReadFromStream"));
            //Write Methods
            WriteMethods.Add(typeof(bool), typeof(BinaryWriter).GetMethod("Write", new Type[]{typeof(bool)}));
            WriteMethods.Add(typeof(byte), typeof(BinaryWriter).GetMethod("Write", new Type[]{typeof(byte)}));
            WriteMethods.Add(typeof(System.SByte), typeof(BinaryWriter).GetMethod("Write", new Type[]{typeof(System.SByte)}));
            WriteMethods.Add(typeof(System.Single), typeof(BinaryWriter).GetMethod("Write", new Type[]{typeof(System.Single)}));
            //WriteMethods.Add(typeof(byte[]), typeof(BinaryWriter).GetMethod("Write", new Type[]{typeof(byte[])}));
            //WriteMethods.Add(typeof(char[]), typeof(BinaryWriter).GetMethod("Write", new Type[]{typeof(char[])}));
            WriteMethods.Add(typeof(System.Int16), typeof(BinaryWriter).GetMethod("Write", new Type[]{typeof(System.Int16)}));
            WriteMethods.Add(typeof(System.Int32), typeof(BinaryWriter).GetMethod("Write", new Type[]{typeof(System.Int32)}));
            WriteMethods.Add(typeof(System.UInt16), typeof(BinaryWriter).GetMethod("Write", new Type[]{typeof(System.UInt16)}));
            WriteMethods.Add(typeof(System.UInt32), typeof(BinaryWriter).GetMethod("Write", new Type[]{typeof(System.UInt32)}));
            WriteMethods.Add(typeof(System.String), typeof(MarshallingMethods).GetMethod("WriteString"));
            WriteMethods.Add(typeof(CustomMarshaler), typeof(CustomMarshaler).GetMethod("WriteToStream"));

  • cusCom.rar (124.7 KB)

            WriteMethods.Add(typeof(bool[]), typeof(MarshallingMethods).GetMethod("WriteArray", new Type[] { typeof(BinaryWriter), typeof(bool[]) }));
            WriteMethods.Add(typeof(char[]), typeof(MarshallingMethods).GetMethod("WriteArray", new Type[] { typeof(BinaryWriter), typeof(char[]) }));
            WriteMethods.Add(typeof(short[]), typeof(MarshallingMethods).GetMethod("WriteArray", new Type[] { typeof(BinaryWriter), typeof(short[]) }));
            WriteMethods.Add(typeof(ushort[]), typeof(MarshallingMethods).GetMethod("WriteArray", new Type[] { typeof(BinaryWriter), typeof(ushort[]) }));
            WriteMethods.Add(typeof(int[]), typeof(MarshallingMethods).GetMethod("WriteArray", new Type[] { typeof(BinaryWriter), typeof(int[]) }));
            WriteMethods.Add(typeof(uint[]), typeof(MarshallingMethods).GetMethod("WriteArray", new Type[] { typeof(BinaryWriter), typeof(uint[]) }));
            WriteMethods.Add(typeof(long[]), typeof(MarshallingMethods).GetMethod("WriteArray", new Type[] { typeof(BinaryWriter), typeof(long[]) }));
            WriteMethods.Add(typeof(ulong[]), typeof(MarshallingMethods).GetMethod("WriteArray", new Type[] { typeof(BinaryWriter), typeof(ulong[]) }));
            WriteMethods.Add(typeof(float[]), typeof(MarshallingMethods).GetMethod("WriteArray", new Type[] { typeof(BinaryWriter), typeof(float[]) }));

        }

        #endregion

        static helper methods#region static helper methods

        public static short[] ReadInt16Array(BinaryReader reader, int count)
        {
            short[] result = new short[count];

            for(int i=0;i            {
                result[i] = reader.ReadInt16();
            }
            return result;
        }

        public static int[] ReadInt32Array(BinaryReader reader, int count)
        {
            int[] result = new int[count];

            for(int i=0;i            {
                result[i] = reader.ReadInt32();
            }
            return result;
        }

        public static ushort[] ReadUInt16Array(BinaryReader reader, int count)
        {
            ushort[] result = new ushort[count];

            for(int i=0;i            {
                result[i] = reader.ReadUInt16();
            }
            return result;
        }

        public static uint[] ReadUInt32Array(BinaryReader reader, int count)
        {
            uint[] result = new uint[count];

            for(int i=0;i            {
                result[i] = reader.ReadUInt32();
            }
            return result;
        }

        public static string ReadString(BinaryReader reader, int count)
        {
            string result = "";
            if (count == 0)
            {
                count = 255; //default   
            }
            char[] data = reader.ReadChars(count);

            result = new string(data).TrimEnd('');
            return result;
        }

        public static void WriteString(BinaryWriter writer, string value, int size)
        {
            if (value!=null)
            {
                byte[] bstring = System.Text.Encoding.Unicode.GetBytes(value.Substring(0, size));
                writer.Write(bstring);
            }
        }

        public static DateTime ReadDateTime(BinaryReader reader)
        {
            return DateTime.FromFileTime(reader.ReadInt64());
        }

        public static void WriteArray(BinaryWriter writer, bool[] arr)
        {
            for (int i = 0; i < arr.Length; i++)
            {
                writer.Write(arr[i]);
            }
        }
        public static void WriteArray(BinaryWriter writer, char[] arr)
        {
            for (int i = 0; i < arr.Length; i++)
            {
                writer.Write(arr[i]);
            }
        }

        public static void WriteArray(BinaryWriter writer, byte[] arr)
        {
            for (int i = 0; i < arr.Length; i++)
            {
                writer.Write(arr[i]);
            }
        }

        public static void WriteArray(BinaryWriter writer, short[] arr)
        {
            for (int i = 0; i < arr.Length; i++)
            {
                writer.Write(arr[i]);
            }
        }
        public static void WriteArray(BinaryWriter writer, ushort[] arr)
        {
            for (int i = 0; i < arr.Length; i++)
            {
                writer.Write(arr[i]);
            }
        }
        public static void WriteArray(BinaryWriter writer, int[] arr)
        {
            for (int i = 0; i < arr.Length; i++)
            {
                writer.Write(arr[i]);
            }
        }
        public static void WriteArray(BinaryWriter writer, uint[] arr)
        {
            for (int i = 0; i < arr.Length; i++)
            {
                writer.Write(arr[i]);
            }
        }
        public static void WriteArray(BinaryWriter writer, long[] arr)
        {
            for (int i = 0; i < arr.Length; i++)
            {
                writer.Write(arr[i]);
            }
        }
        public static void WriteArray(BinaryWriter writer, ulong[] arr)
        {
            for (int i = 0; i < arr.Length; i++)
            {
                writer.Write(arr[i]);
            }
        }
        public static void WriteArray(BinaryWriter writer, float[] arr)
        {
            for (int i = 0; i < arr.Length; i++)
            {
                writer.Write(arr[i]);
            }
        }

        public static void WriteSerializers(BinaryWriter writer, CustomMarshaler[] arr)
        {
            for (int i = 0; i < arr.Length; i++)
            {
                arr[i].WriteToStream(writer);
            }
        }

        #endregion
    }

    #endregion

    CustomMarshalAsAttribute#region CustomMarshalAsAttribute
    /**////
    /// CustomMarshalAsAttribute implementaion.
    ///
    public sealed class CustomMarshalAsAttribute : Attribute
    {
        public int SizeConst = 0;
        public string  SizeField = null;
    }

    #endregion

}

MIB_IFROW.cs
using System;
using System.Collections.Generic;
using , System.Text;

namespace Lemony.SystemInfo
{
    public class MIB_IFROW : CustomMarshaler
    {
        [CustomMarshalAs(SizeConst = MAX_INTERFACE_NAME_LEN)]
        public string wszName;
        public uint dwIndex; // index of the interface
        public uint dwType; // type of interface
        public uint dwMtu; // max transmission unit
        public uint dwSpeed; // speed of the interface
        public uint dwPhysAddrLen; // length of physical address
        [CustomMarshalAs(SizeConst = MAXLEN_PHYSADDR)]
        public byte[] bPhysAddr; // physical address of adapter
        public uint dwAdminStatus; // administrative status
        public uint dwOperStatus; // operational status
        public uint dwLastChange; // last time operational status changed
        public uint dwInOctets; // octets received
        public uint dwInUcastPkts; // unicast packets received
        public uint dwInNUcastPkts; // non-unicast packets received
        public uint dwInDiscards; // received packets discarded
        public uint dwInErrors; // erroneous packets received
        public uint dwInUnknownProtos; // unknown protocol packets received
        public uint dwOutOctets; // octets sent
        public uint dwOutUcastPkts; // unicast packets sent
        public uint dwOutNUcastPkts; // non-unicast packets sent
        public uint dwOutDiscards; // outgoing packets discarded
        public uint dwOutErrors; // erroneous packets sent
        public uint dwOutQLen; // output queue length
        public uint dwDescrLen; // length of bDescr member
        [CustomMarshalAs(SizeConst = MAXLEN_IFDESCR)]
        public byte[] bDescr; // interface description        

        private const int MAX_INTERFACE_NAME_LEN = 256;
        private const int MAXLEN_PHYSADDR = 8;
        private const int MAXLEN_IFDESCR = 256;
        private const int MAX_ADAPTER_NAME = 128;
    }
}

MIB_IFTABLE.cs
using System;
using System.Collections.Generic;
using System.Text;

namespace Lemony.SystemInfo
{
    /**////
    /// IFTable
    ///
    public class MIB_IFTABLE : CustomMarshaler
    {
        public int dwNumEntries;
        [CustomMarshalAs(SizeField = "dwNumEntries")]
        public MIB_IFROW[] Table;

        public MIB_IFTABLE()
        {
            this.data = new byte[this.GetSize()];
        }

        public MIB_IFTABLE(int size)
        {
            this.data = new byte[size];
        }
    }
}

再定义一个 NetInfo 类,存储网络信息

NetInfo.cs
using System;
using System.Collections.Generic;
using System.Text;
using System.Runtime.InteropServices;

namespace Lemony.SystemInfo
{
    /**////
    /// 网络类型
    ///
    public enum NetType
    {
        Other = 1,
        Ethernet = 6,
        Tokenring = 9,
        FDDI = 15,
        PPP = 23,
        Loopback = 24,
        Slip = 28
    };

    /**////
    /// 网络状态
    ///
    public enum NetState
    {
        NotOperational = 0,
        Operational = 1,
        Disconnected = 2,
        Connecting = 3,
        Connected = 4,
        Unreachable = 5
    };

    /**////
    /// 网络信息类
    ///
    public class NetInfo
    {
        public NetInfo()
        {
        }

        private string m_Name;
        /**////
        /// 名称
        ///
        public string Name
        {
            get { return m_Name; }
            set { m_Name = value; }
        }

        private uint m_Index;
        /**////
        /// 有效编号
        ///
        public uint Index
        {
            get { return m_Index; }
            set { m_Index = value; }
        }

        private NetType m_Type;
        /**////
        /// 类型
        ///
        public NetType Type
        {
            get { return m_Type; }
            set { m_Type = value; }
        }

        private uint m_Speed;
        /**////
        /// 速度
        ///
        public uint Speed
        {
            get { return m_Speed; }
            set { m_Speed = value; }
        }

        private uint m_InOctets;
        /**////
        /// 总接收字节数
        ///
        public uint InOctets
        {
            get { return m_InOctets; }
            set { m_InOctets = value; }
        }

        private uint m_OutOctets;
        /**////
        /// 总发送字节数
        ///
        public uint OutOctets
        {
            get { return m_OutOctets; }
            set { m_OutOctets = value; }
        }

        private NetState m_Status;
        /**////
        /// 操作状态
        ///
        public NetState Status
        {
            get { return m_Status; }
            set { m_Status = value; }
        }

        private uint m_InErrors;
        /**////
        /// 总错收字节数
        ///
        public uint InErrors
        {
            get { return m_InErrors; }
            set { m_InErrors = value; }
        }

        private uint m_OutErrors;
        /**////
        /// 总错发字节数
        ///
        public uint OutErrors
        {
            get { return m_OutErrors; }
            set { m_OutErrors = value; }
        }

        private uint m_InUnknownProtos;
        /**////
        /// 未知协议共收字节数
        ///
        public uint InUnknownProtos
        {
            get { return m_InUnknownProtos; }
            set { m_InUnknownProtos = value; }
        }

        private string m_PhysAddr;
        /**////
        /// 物理地址
        ///
        public string PhysAddr
        {
            get { return m_PhysAddr; }
            set { m_PhysAddr = value; }
        }

    }
}

OK,现在可以获取网络信息了

        /**////
        /// Get IFTable
        ///
        /// MIB_IFTABLE Class
        private static MIB_IFTABLE GetAllIfTable()
        {
            //缓冲区大小
            uint dwSize = 0;

            //获取缓冲区大小
            uint ret = GetIfTable(null, ref dwSize, false);
            if (ret == 50)
            {
                //此函数仅支持于 win98/nt 系统
                return null;
            }

            //定义,获取 MIB_IFTABLE 对象
            MIB_IFTABLE tbl = new MIB_IFTABLE((int)dwSize);
            ret = GetIfTable(tbl.ByteArray, ref dwSize, false);

            //如果不成功
            if (ret != 0)
            {
                return null;
            }

            return tbl;
        }

        /**////
        /// Get NetInfo Class
        ///
        /// MIB_IFROW Class
        /// NetInfo Class
        private static NetInfo GetNetInfo(MIB_IFROW row)
        {
            NetInfo ninfo = new NetInfo();
            ninfo.Index = row.dwIndex;
            ninfo.Name = Encoding.ASCII.GetString(row.bDescr, 0, (int)row.dwDescrLen);
            ninfo.PhysAddr = GetPhysAddr(row.bPhysAddr, (int)row.dwPhysAddrLen);
            ninfo.Type = (NetType)row.dwType;
            ninfo.Status = (NetState)row.dwOperStatus;
            ninfo.Speed = row.dwSpeed;
            ninfo.InErrors = row.dwInErrors;
            ninfo.InOctets = row.dwInOctets;
            ninfo.InUnknownProtos = row.dwInUnknownProtos;
            ninfo.OutErrors = row.dwOutErrors;
            ninfo.OutOctets = row.dwOutOctets;
            return ninfo;
        }
/**////
        /// 获取所有的网络信息
        ///
        /// NetInfo 网络信息范型
        public static List GetAllNetInfo()
        {
            //定义范型
            List ninfos = new List();

            //定义,获取 MIB_IFTABLE 对象
            MIB_IFTABLE tbl = GetAllIfTable();

            //如果成功
            if (tbl != null)
            {
                tbl.Deserialize();
                for (int i = 0; i < tbl.Table.Length; i++)
                {
                    ninfos.Add(GetNetInfo(tbl.Table[i]));
                }
            }

            return ninfos;
        }
PS:事实上,我把获取网络、CPU、内存、磁盘、进程信息等功能封装起来,并做了一个比较完善的 Windows 任务管理器,整理完后发布源码。

<> <>

本文由10bet手机官网发布于微服架构,转载请注明出处:socket通信较完善方案,UMD手机电子书的读取和制作源码

上一篇:没有了 下一篇:web应用程序打包,并自动安装SQL数据库
猜你喜欢
热门排行
精彩图文