1、方法说明: 客户端的项目下新建了一个名为message的类,这个类目前只有一个功能方法,这个方法的作用就是将发送的数据添加上数据信息的长度,将保存数据长度信息的数据用4个字节来表示BitCoverter.GetBytes(),通过这个函数即可实现转换。 2、代码:
///
/// 方法的作用就是将发送的数据添加上数据信息的长度
///
namespace TCP客户端
{
class Message
{
public static byte[] GetBytes(string data)
{
byte[] dataBytes = Encoding.UTF8.GetBytes(data);//将数据转换成byte数组。
int dataLength = dataBytes.Length;//获得数据byte数组的长度。
byte[] lengthBytes = BitConverter.GetBytes(dataLength);//将长度转换成4个字节byte数组。
byte[] newBytes = lengthBytes.Concat(dataBytes).ToArray();//将长度数组和数据数组进行连接。
return newBytes;
}
}
}