C#TCP通信 客户端发送结构体出错
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Net;
using System.Net.Sockets;
using System.Threading;
using System.Runtime.InteropServices;
namespace Robot_Client
{
[StructLayoutAttribute(LayoutKind.Sequential, CharSet = CharSet.Ansi, Pack = 1)]
public partial class Form1 : Form
{
public Socket newclient_Client; //用于tcp通讯
bool Connected_Client = false; //用于判断是否连接
public Thread myThread_client;//用于监听
public delegate void SetlblHandle(string str);
public struct SRobot
{
public float x;
public float y;
public float z;
public float a;
public float b;
public float c;
public float aux1;
public float aux2;
public float aux3;
public int mode;
}
public static byte[] StructToBytes(object structObj)
{
//得到结构体的大小
int size = Marshal.SizeOf(structObj);
//创建byte数组
byte[] bytes = new byte[size];
//分配结构体大小的内存空间
IntPtr structPtr = Marshal.AllocHGlobal(size);
//将结构体拷到分配好的内存空间
Marshal.StructureToPtr(structObj, structPtr, false);
//从内存空间拷到byte数组
Marshal.Copy(structPtr, bytes, 0, size);
//释放内存空间
Marshal.FreeHGlobal(structPtr);
//返回byte数组
return bytes;
}
public static object BytesToStuct(byte[] bytes, Type type)
{
//得到结构体的大小
int size = Marshal.SizeOf(type);
//byte数组长度小于结构体的大小
if (size > bytes.Length)
{
//返回空
return null;
}
//分配结构体大小的内存空间
IntPtr structPtr = Marshal.AllocHGlobal(size);
//将byte数组拷到分配好的内存空间
Marshal.Copy(bytes, 0, structPtr, size);
//将内存空间转换为目标结构体
object obj = Marshal.PtrToStructure(structPtr, type);
//释放内存空间
Marshal.FreeHGlobal(structPtr);
//返回结构体
return obj;
}
public Form1()
{
InitializeComponent();
//IPAddress[] serverIPs = Dns.GetHostAddresses("");
//txbServerIP.Text = serverIPs[1].ToString(); //机器人IP地址
}
public void ConnectRobot()//链接tcp
{
byte[] data = new byte[1024];
newclient_Client = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
int port = Convert.ToInt32("8116");//端口号
IPEndPoint ie = new IPEndPoint(IPAddress.Parse("192.168.0.103"), port);
try
{
newclient_Client.Connect(ie);
Connected_Client = true;
b_click_connect.Enabled = false;
//sendToRobot("as\r\n");//建立连接后,首先发送as,则可以通过计算机发送as语言指令
SetTishi("机器人连接成功...");//显示
}
catch (SocketException e)
{
SetTishi("连接机器人失败 " + e.Message);
return;
}
ThreadStart myThreaddelegate = new ThreadStart(ReceiveMsg);
myThread_client = new Thread(myThreaddelegate);
myThread_client.Start();
}
public void ReceiveMsg()//监听tcp
{
int thelastData = 999;
while (true)
{
byte[] data = new byte[1024];
int recv = newclient_Client.Receive(data);//接收消息
string stringdata = Encoding.UTF8.GetString(data, 0, recv);//将bytes转换为字符
SetTishi(stringdata);
//string stringdata = Encoding.Unicode.GetString(data, 0, recv);
if (stringdata == "")//判断是否端口连接
{
SetTishi("服务器已退出");
newclient_Client.Close();
Connected_Client = false;
break;
}
}
}
public void SetTishi(string msg)//显示信息
{
{
//在线程里以安全方式调用控件
if (textBox1.InvokeRequired)
{
textBox1.Invoke(new SetlblHandle(SetTishi), msg);
}
else
{
//在当前文本框内追加信息
if (textBox1.Text.Length > 5000)//如果信息太多则清空
{
textBox1.Clear();
}
//添加时间显示
//string itime = DateTime.Now.ToString("HH:mm:ss");
textBox1.SelectionStart = textBox1.TextLength;
textBox1.ScrollToCaret();
textBox1.AppendText(/*itime + " " + */msg + "\n");
}
}
}
private void b_click_connect_Click(object sender, EventArgs e)
{
ConnectRobot();
}
private void button1_Click(object sender, EventArgs e)
{
//SRobot s1;
//s1.mode = 1;
//byte[] data = new byte[1024];
//data = BitConverter.GetBytes(s1.mode);
// newclient_Client.Send(data);
}
private void button2_Click(object sender, EventArgs e)
{
SRobot s1=new SRobot();
s1.a = 0;
s1.b = 0;
s1.c = 0;
s1.aux1 = 0;
s1.aux2 = 0;
s1.aux3 = 0;
s1.mode = 1;
newclient_Client.Send(StructToBytes(s1));
}
private void button3_Click(object sender, EventArgs e)
{
}
}
}
编译完成后提示:“System.TypeLoadException”类型的未经处理的异常在 mscorlib.dll 中发生
其他信息: 因为格式无效,未能从程序集“Robot_Client, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null”中加载类型“Robot_Client.Form1”。