C#文件阅读和发送通过套接字 [英] c# file read and send over socket
问题描述
这是我如何发送邮件使用的文件的的NetworkStream
。
This is how I send a file using a NetworkStream
.
private void go()
{
byte[] send = File.ReadAllBytes("example.txt");
ns.Write(send, 0, send.Length);
}
NS
是一个的NetworkStream
现在我想知道我怎么能接收和阅读传入<$ C $,当然。 C>的NetworkStream ?
Now I would like to know how I could receive and read an incoming NetworkStream
?
我知道,我需要指定一个缓冲区从这样的阅读,
I know that I need to specify a buffer to read from like this,
ns.Read(buffer,0,buffer.length).
但缓冲区应该在那里?
but which buffer should be there?
推荐答案
TCP是一个面向流的协议,这意味着有像UDP没有应用程序的消息的格式。因此,你不能真正通过TCP本身在那里的应用程序消息结束检测。
TCP is a stream based protocol, which means that there is no notation of application messages like in UDP. Thus you cannot really detect by TCP itself where an application message ends.
因此,你需要引入某种形式的检测。通常,您添加后缀(新线,分号或其他)或长的头。
Therefore you need to introduce some kind of detection. Typically you add a suffix (new line, semicolon or whatever) or a length header.
在这种情况下,更容易增加长度的头既然选择后缀可能被发现在该文件中的数据
In this case it's easier to add a length header since the chosen suffix could be found in the file data.
所以,发送文件是这样的:
So sending the file would look like this:
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);
}
在接收端它,你从读检查返回值的内容是非常重要的可以进来块:
On the receiver side it's important that you check the return value from Read as contents can come in chunks:
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;
}
这篇关于C#文件阅读和发送通过套接字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!