如何才能永远等待信号?
IPAddress serverAddress = IPAddress.Parse("192.168.1.66");
const int serverPort = 7777;
string filename = "test.txt";
using var client = new TcpClient(serverAddress.ToString(), serverPort);
using var stream = client.GetStream();
byte[] buf = new byte[65536];
await ReadBytes(sizeof(long));
long remainingLength = IPAddress.NetworkToHostOrder(BitConverter.ToInt64(buf, 0));
using var file = File.Create(filename);
while (remainingLength > 0)
{
int lengthToRead = (int)Math.Min(remainingLength, buf.Length);
await ReadBytes(lengthToRead);
await file.WriteAsync(buf, 0, lengthToRead);
remainingLength -= lengthToRead;
}
async Task ReadBytes(int howmuch)
{
int readPos = 0;
while (readPos < howmuch)
{
var actuallyRead = await stream.ReadAsync(buf, readPos, howmuch - readPos);
if (actuallyRead == 0)
throw new EndOfStreamException();
readPos += actuallyRead;
}
}
在等待来自服务器端口的文件时,我需要无限等待信号
Await 等待 20 秒,然后杀死程序
如果删除这些行也许会有所帮助:
if (actuallyRead == 0)
throw new EndOfStreamException();
此外,循环的值也受到限制。如果您不需要这个值,您也可以使用无限循环:
while (true)
{
...
}