首页 > 解决方案 > 无法通过 tcp 在结构中发送字符串变量

问题描述

我在服务器和客户端上有结构:

[StructLayout(LayoutKind.Explicit)]
public struct ObserverStrings
{
   [FieldOffset(0)]
   public int id;
   [FieldOffset(8)]
   public string info;
}

通过 id 我了解收到了哪些信息。

在客户端,我发送 id = -3 的信息

ObserverStrings observerStrings = new ObserverStrings {
    id = -3,
    info = "This is info"
};
byte[] data = WriteStruct(observerStrings);
stream.Write(dota, 0, data.Length);

在服务器上我收到它

ObserverStrings os = ReadStruct<ObserverStrings>(RecievedData, 0, bytes); 

public T ReadStruct<T>(byte[] buffer, int index, int count)
{
     byte[] tempBuffer = new byte[count];
     for (int i = 0; i < count; i++) {
         tempBuffer[i] = buffer[index + i];
     }
     GCHandle handle = GCHandle.Alloc(tempBuffer, GCHandleType.Pinned);
     T temp = (T)Marshal.PtrToStructure(handle.AddrOfPinnedObject(), typeof(T));
     handle.Free();
     return temp;
}

在此之后,我得到“尝试读取或写入受保护的内存。这通常表明其他内存已损坏”或 id = -3 以及一些与我发送的字符串相距甚远的字符串。

我也试过:

StringBuilder builder = new StringBuilder();
builder.Append(Encoding.Unicode.GetString(Measure, 8, bytes - 8));
string[] mesInfo = builder.ToString(); 

但也得到 id = -3 和一些离我发送的字符串很远的字符串。

标签: c#winforms

解决方案


推荐阅读