通过套接字发送整数字节数组
本文关键字:字节 字节数 数组 整数 套接字 | 更新日期: 2023-09-27 17:53:16
是否有一种方法来发送一系列int作为一个整体在一个单一的bytearray和在客户端,削减bytearray在4乘4个字节,以便我可以检索回值?我一直在尝试,但到目前为止,我只能通过一次发送一个值来做到这一点。谢谢。
public void SendData_Click(System.Object sender, System.EventArgs e)
{
int value = 500;
int value2 = 1000;
int value3 = 1500;
int[] valueStore = new int[3];
valueStore[0] = value;
valueStore[1] = value2;
valueStore[2] = value3;
for (int i = 0; i < 3; i++)
{
byte[] array = BitConverter.GetBytes(valueStore[i]);
byte[] outStream = array;
serverStream.Write(outStream, 0, outStream.Length);
serverStream.Flush();
}
}
您可以使用BinaryWriter将整数写入流,该流可以在发送之前轻松转换为字节数组。见下文:
int value = 500;
int value2 = 1000;
int value3 = 1500;
System.IO.MemoryStream ms = new System.IO.MemoryStream();
System.IO.BinaryWriter bw = new System.IO.BinaryWriter(ms);
bw.Write(value);
bw.Write(value2);
bw.Write(value3);
byte[] array = ms.ToArray();
serverStream.Write(array, 0, array.Length);
serverStream.Flush();
要读取另一侧的值,使用:
System.IO.MemoryStream ms = new System.IO.MemoryStream(array);
System.IO.BinaryReader br = new System.IO.BinaryReader(ms);
int value = br.ReadInt32();
int value2 = br.ReadInt32();
int value3 = br.ReadInt32();
使用BinaryWriter
:
byte[] bytes;
using (var ms = new MemoryStream())
using (var bw = new BinaryWriter(ms))
{
for (int i = 0; i < 3; i++)
bw.Write(valueStore[i]);
bytes = ms.ToArray();
}
serverStream.Write(bytes, 0, bytes.Length);