c#文件读取并通过套接字发送
这是我使用NetworkStream
发送文件的方式。
private void go() { byte[] send = File.ReadAllBytes("example.txt"); ns.Write(send, 0, send.Length); }
ns
当然是一个NetworkStream
。
现在我想知道如何接收和读取传入的NetworkStream
?
我知道我需要指定一个缓冲区来读取这样的,
ns.Read(buffer,0,buffer.length).
但哪个缓冲区应该在那里?
TCP是基于流的协议,这意味着没有像UDP中那样的应用程序消息的表示法。 因此,您无法通过TCP本身检测应用程序消息结束的位置。
因此,您需要引入某种检测。 通常,您添加后缀(新行,分号或其他)或长度标题。
在这种情况下,添加长度标题更容易,因为可以在文件数据中找到所选的后缀。
所以发送文件看起来像这样:
private void SendFile(string fileName, NetworkStream ns) { var bytesToSend = File.ReadAllBytes(fileName); var header = BitConverter.GetBytes(bytesToSend.Length); ns.Write(header, 0, header.Length); ns.Write(bytesToSend, 0, bytesToSend.Length); }
在接收方,重要的是检查Read的返回值,因为内容可以是块状:
public byte[] ReadFile(NetworkStream ns) { var header = new byte[4]; var bytesLeft = 4; var offset = 0; // have to repeat as messages can come in chunks while (bytesLeft > 0) { var bytesRead = ns.Read(header, offset, bytesLeft); offset += bytesRead; bytesLeft -= bytesRead; } bytesLeft = BitConverter.ToInt32(header, 0); offset = 0; var fileContents = new byte[bytesLeft]; // have to repeat as messages can come in chunks while (bytesLeft > 0) { var bytesRead = ns.Read(fileContents, offset, bytesLeft); offset += bytesRead; bytesLeft -= bytesRead; } return fileContents; }