[英]How to give a sign and exit infinitive loop when sending file via socket
我正在尝试从cleint发送文本文件并将其写入服务器端,但是我不确定如何退出不定式while(true)循环。 这是我的代码,非常简单。
客户
byte[] msg = File.ReadAllBytes(@"C:\TCPIP\test_big.txt");
int bytesSent = sender.Send(msg);
服务器
while (true)
{
Console.WriteLine("Waiting for a connection...");
// Program is suspended while waiting for an incoming connection.
Socket handler = listener.Accept();
data = null;
string outputPath = @"C:\output\2.txt";
while (true)
{
bytes = new byte[1024];
int bytesRec = handler.Receive(bytes);
data += Encoding.ASCII.GetString(bytes, 0, bytesRec);
//I need a "break;" here...
}
File.WriteAllText(outputPath, data);
Console.WriteLine(File.Exists(outputPath) ? "File received." : "File not received.");
handler.Shutdown(SocketShutdown.Both);
handler.Close();
}
我使用了MSDN中的示例...
所以,我的问题是,当我收到所有字节时如何退出while循环? 谢谢。
如果输入的数据为空,则停止读取
while (true)
{
bytes = new byte[1024];
int bytesRec = handler.Receive(bytes);
if(bytesRec <= 0)
break;
data += Encoding.ASCII.GetString(bytes, 0, bytesRec);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.