1. 同样, 我们先看看这一个比简单的 结构体
代码
using System;
using System.Collections.Generic;
using System.Text;
using System.Runtime.InteropServices;
namespace CSharp_Socket_5
{
/// <summary>
/// 通信消息格式
/// </summary>
[Serializable]
[StructLayout(LayoutKind.Sequential, Pack = 1)]
public struct CP2PMessage
{
public ushort id;
}
}
using System.Collections.Generic;
using System.Text;
using System.Runtime.InteropServices;
namespace CSharp_Socket_5
{
/// <summary>
/// 通信消息格式
/// </summary>
[Serializable]
[StructLayout(LayoutKind.Sequential, Pack = 1)]
public struct CP2PMessage
{
public ushort id;
}
}
C++ 版本
struct CP2PMessage
{
WORD id;
};
{
WORD id;
};
2. C# 服务端, 和之前的一样滴~~ 看来是不是很亲切也~
代码
using System;
using System.Collections.Generic;
using System.Text;
using System.Net.Sockets;
using System.Net;
using System.Runtime.InteropServices;
namespace CSharp_Socket_5
{
class Program
{
/// <summary>
/// 服务端
/// </summary>
/// <param name="args"></param>
static void Main(string[] args)
{
// 1.创建套节字
Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
// 2.填充IP
IPEndPoint ipe = new IPEndPoint(IPAddress.Any, 4321);
// 3.绑定
socket.Bind(ipe);
// 等待客户机连接
Console.WriteLine("这个服务器, host name is {0}", Dns.GetHostName());
Console.WriteLine("等待客户端连接....");
// 4.得客户机IP
IPEndPoint sender = new IPEndPoint(IPAddress.Any, 0);
EndPoint remote = (EndPoint)sender;
// 5.接收客户机数据
byte[] buffer = new byte[1024];
socket.ReceiveFrom(buffer, ref remote);
CP2PMessage msg = new CP2PMessage();
msg = (CP2PMessage)BytesToStruct(buffer, msg.GetType());
Console.WriteLine("接C++收的值为:{0}", msg.id);
Console.ReadKey();
}
public static byte[] StructToBytes(object obj)
{
int size = Marshal.SizeOf(obj);
byte[] bytes = new byte[size];
IntPtr structPtr = Marshal.AllocHGlobal(size); //分配结构体大小的内存空间
Marshal.StructureToPtr(obj, structPtr, false); //将结构体拷到分配好的内存空间
Marshal.Copy(structPtr, bytes, 0, size); //从内存空间拷到byte数组
Marshal.FreeHGlobal(structPtr); //释放内存空间
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;
}
}
}
using System.Collections.Generic;
using System.Text;
using System.Net.Sockets;
using System.Net;
using System.Runtime.InteropServices;
namespace CSharp_Socket_5
{
class Program
{
/// <summary>
/// 服务端
/// </summary>
/// <param name="args"></param>
static void Main(string[] args)
{
// 1.创建套节字
Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
// 2.填充IP
IPEndPoint ipe = new IPEndPoint(IPAddress.Any, 4321);
// 3.绑定
socket.Bind(ipe);
// 等待客户机连接
Console.WriteLine("这个服务器, host name is {0}", Dns.GetHostName());
Console.WriteLine("等待客户端连接....");
// 4.得客户机IP
IPEndPoint sender = new IPEndPoint(IPAddress.Any, 0);
EndPoint remote = (EndPoint)sender;
// 5.接收客户机数据
byte[] buffer = new byte[1024];
socket.ReceiveFrom(buffer, ref remote);
CP2PMessage msg = new CP2PMessage();
msg = (CP2PMessage)BytesToStruct(buffer, msg.GetType());
Console.WriteLine("接C++收的值为:{0}", msg.id);
Console.ReadKey();
}
public static byte[] StructToBytes(object obj)
{
int size = Marshal.SizeOf(obj);
byte[] bytes = new byte[size];
IntPtr structPtr = Marshal.AllocHGlobal(size); //分配结构体大小的内存空间
Marshal.StructureToPtr(obj, structPtr, false); //将结构体拷到分配好的内存空间
Marshal.Copy(structPtr, bytes, 0, size); //从内存空间拷到byte数组
Marshal.FreeHGlobal(structPtr); //释放内存空间
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;
}
}
}
3. 重点了,,C++ 客户端
代码
#include <winsock2.h>
#include <stdio.h>
#pragma comment(lib, "WS2_32.lib")
struct CP2PMessage
{
WORD id;
};
void main()
{
//初始化 WS2_32.dll
WSADATA wsaData;
::WSAStartup(MAKEWORD(2,2), & wsaData);
// 1.创建套节字
SOCKET s = ::socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
// 2.填写服务器IP
sockaddr_in sin;
sin.sin_family = AF_INET;
sin.sin_port = ::htons(4321);
sin.sin_addr.S_un.S_addr = ::inet_addr("127.0.0.1");
// 3. 向服务器发送消息
CP2PMessage msg;
msg.id = 10;
::sendto(s, (char*)&msg, sizeof(msg), 0, (sockaddr*)&sin, sizeof(sin));
}
#include <stdio.h>
#pragma comment(lib, "WS2_32.lib")
struct CP2PMessage
{
WORD id;
};
void main()
{
//初始化 WS2_32.dll
WSADATA wsaData;
::WSAStartup(MAKEWORD(2,2), & wsaData);
// 1.创建套节字
SOCKET s = ::socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
// 2.填写服务器IP
sockaddr_in sin;
sin.sin_family = AF_INET;
sin.sin_port = ::htons(4321);
sin.sin_addr.S_un.S_addr = ::inet_addr("127.0.0.1");
// 3. 向服务器发送消息
CP2PMessage msg;
msg.id = 10;
::sendto(s, (char*)&msg, sizeof(msg), 0, (sockaddr*)&sin, sizeof(sin));
}
4. 完成了,,,这么, 请看效果图!!