如何通过套接字tcp从客户端到服务器和服务器向客户端发送字符串数组?我找不到任何解决方案......我试图将字符串数组转换为字节数组并返回。但是我得到了记忆力不足......
private static byte[] ToByteArray(string[] input)
{
using (var stream = new MemoryStream())
using (var writer = new BinaryWriter(stream, Encoding.UTF8))
{
var rows = input.GetLength(0);
writer.Write(rows);
for (int i = 0; i < rows; i++)
{
writer.Write(input[i]);
}
return stream.ToArray();
}
}
private static string[] FromByteArray(byte[] input)
{
using (var stream = new MemoryStream(input))
using (var reader = new BinaryReader(stream, Encoding.UTF8))
{
var rows = reader.ReadInt32();
var result = new string[rows];
for (int i = 0; i < rows; i++)
{
result[i] = reader.ReadString();
}
return result;
}
}
答案 0 :(得分:1)
在编写二进制数据时,BinaryWriter在调用MemoryStream.ToArray()
时仍然可以包含缓冲数据。这会导致具有二进制数据的数组不完整。首先刷新BinaryWriter
:
writer.Flush();
return stream.ToArray();