using System;< xmlnamespace prefix ="o" ns ="urn:schemas-microsoft-com:office:office" />

using System.Net.Sockets;

using System.Net;

using System.IO;

using System.Diagnostics;

using System.Threading;

using System.Runtime.InteropServices;

using System.Text;

using System.Windows.Forms;



namespace daniu

{



public class DNA

{

[StructLayout(LayoutKind.Sequential, Pack = 1)]

public struct PaketHead //結構體:包頭
{

[MarshalAs(UnmanagedType.ByValArray, SizeConst = 3)]

public byte[] cmd;

[MarshalAs(UnmanagedType.ByValArray, SizeConst = 64)]

public byte[] para1;

[MarshalAs(UnmanagedType.ByValArray, SizeConst = 64)]

public byte[] para2;

}



protected byte[] Struct2Bytes(Object obj) //把結構體struct轉化為Bytes

{

int size = Marshal.SizeOf(obj);

//創建byte陣列
byte[] bytes = new byte[size];

//分配結構體大小的記憶體空間
IntPtr structPtr = Marshal.AllocHGlobal(size);

//將結構體拷到分配好的記憶體空間
Marshal.StructureToPtr(obj, structPtr, false);

//從記憶體空間拷到byte陣列
Marshal.Copy(structPtr, bytes, 0, size);

//釋放記憶體空間
Marshal.FreeHGlobal(structPtr);

//返回byte陣列
return bytes;

}



protected object Bytes2Struct(byte[] bytes) //把Bytes轉化為Struct

{

//得到結構的大小

int size = Marshal.SizeOf(typeof(PaketHead));

//byte陣列長度小於結構的大小

if (size > bytes.Length)

{

//返回空

return null;

}

//分配結構大小的記憶體空間

IntPtr structPtr = Marshal.AllocHGlobal(size);

//將byte陣列拷到分配好的記憶體空間

Marshal.Copy(bytes, 0, structPtr, size);

//將記憶體空間轉換為目標結構

//這樣是對的

Object temp = null;

try

{

temp = Marshal.PtrToStructure(structPtr, typeof(PaketHead));

}

catch (System.Exception e)

{

MessageBox.Show(e.Message);

}



//釋放記憶體空間

Marshal.FreeHGlobal(structPtr);

//返回結構

return temp;

//IntPtr arrPtr = Marshal.UnsafeAddrOfPinnedArrayElement(bytes, 0);

//return Marshal.PtrToStructure(arrPtr, typeof(PaketHead));



}



//讀取 包頭
protected void ReadPacketHead(BinaryReader ClientReader, BinaryWriter ClientWriter)

{

byte[] test = null;

test = ClientReader.ReadBytes(200); //二進位讀取物件—— 讀到——byte

PaketHead Paket=(PaketHead)Bytes2Struct(test); //轉化


Console.WriteLine(System.Text.Encoding.UTF8.GetString(Paket.cmd,0,2));

Console.WriteLine(System.Text.Encoding.UTF8.GetString(Paket.para1, 0, 11));

Console.WriteLine(System.Text.Encoding.UTF8.GetString(Paket.para2, 0, 10));



/////////////////////////////////

// test = Struct2Bytes(Paket); //轉化,併發送
// ClientWriter.Write(test);

}



public static void Main(String[] arg)

{

IPAddress _ip = Dns.GetHostAddresses(Dns.GetHostName())[0];

TcpListener mylisten = new TcpListener(_ip, 8888);

Console.WriteLine("開始監聽。。。。。。");

mylisten.Start();

Socket newClient = mylisten.AcceptSocket();

Console.WriteLine("接受到用戶端的請求!正在處理資料。。。。");

NetworkStream stream = new NetworkStream(newClient, true);

BinaryReader br = new BinaryReader(stream);

BinaryWriter bw = new BinaryWriter(stream);

DNA mytest = new DNA();

mytest.ReadPacketHead(br,bw);

Thread.Sleep(1000000);

}

}

}
創作者介紹

資訊園

shadow 發表在 痞客邦 PIXNET 留言(0) 人氣()