服務端代碼:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows.Forms;
using System.Text;
using System.Net;
using System.Net.Sockets;
using System.Threading;
using System.Runtime.InteropServices;
namespace UdpMc
{
struct Data
{
public string longitude;//經度
public string altitude;//高度
public string latitude;//緯度
};
static class Program
{
/// <summary>
/// 應用程序的主入口點。
/// </summary>
[STAThread]
static void Main()
{
//Application.EnableVisualStyles();
//Application.SetCompatibleTextRenderingDefault(false);
//Application.Run(new Form1());
Data structobj = new Data();
structobj.longitude = "121.22";
structobj.altitude = "121.33";
structobj.latitude = "121.44";
byte[] buf = StructToBytes(structobj);
UdpClient client = new UdpClient();//建立發送端的UdpClient實例
IPEndPoint multicast = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 7788);//設置IP地址和端口
//string msg = "123";
//byte[] buf = Encoding.Default.GetBytes(msg);
client.Send(buf, buf.Length, multicast);
}
//發送時將結構體數據轉換成字節數組
public static byte[] StructToBytes(object obj)
{
//得到結構體的大小
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;
}
}
}
客戶端接收時對數據的處理:
//接收的時候需要把字節數組轉換成結構
public static object BytesToStruct(byte[] bytes, Type type)
{
int size = Marshal.SizeOf(type);
if (size > bytes.Length)
return null;
IntPtr structPtr = Marshal.AllocHGlobal(size); //分配結構大小的內存空間
Marshal.Copy(bytes, 0, structPtr, size); //將byte數組拷到分配好的內存空間
object obj = Marshal.PtrToStructure(structPtr, type);
Marshal.FreeHGlobal(structPtr);
return obj;
}