如何安全地结束NetworkStream.Read()?(在C#或VB.net中)
本文关键字:VB net NetworkStream 何安全 安全 结束 Read | 更新日期: 2023-09-27 18:00:46
我写了一个类,试图读取服务器发送的字节数据,当我的应用程序结束时,我也希望循环结束,但如果没有可用的数据,NetworkStream.Read()
似乎只是等待。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net.Sockets;
using System.Threading;
using System.Net;
using System.Threading.Tasks;
namespace Stream
{
class Program
{
private static TcpClient client = new TcpClient("127.0.0.1", 80);
private static NetworkStream stream = client.GetStream();
static void Main(string[] args)
{
var p = new Program();
p.Run();
}
void Run()
{
ThreadPool.QueueUserWorkItem(x =>
{
while (true)
{
stream.Read(new byte[64], 0, 64);
}
});
client.Close();
// insert Console.ReadLine(); if you want to see an exception occur.
}
}
}
有了这个代码,我们就能得到
System.IO.IOException
表示"无法从传输连接读取数据:远程主机强制关闭了现有连接"ObjectDisposedException
表示"无法访问已处理的对象",或System.IO.IOException
表示"对WSACancelBlockingCall的调用中断了阻塞操作"
那么,我该如何安全地结束这种方法呢?
从我运行程序时看到的情况来看,您的第一个异常"无法从传输连接读取数据…"不是由Stream引发的,而是由TcpClient的构造函数引发的,很可能是因为127.0.0.1:80上没有服务器接受连接。
现在,如果你想在Stream.Read上很好地结束,我会异步完成。通过这种方式,您可以捕获读取过程中抛出的任何异常,并相应地清理程序。这是您的程序的修改版本:
using System;
using System.Net.Sockets;
namespace Stream
{
class Program
{
private static TcpClient client;
private static NetworkStream stream;
static void Main(string[] args)
{
var p = new Program();
p.Run();
}
void Run()
{
try
{
client = new TcpClient("127.0.0.1", 80);
stream = client.GetStream();
byte[] buffer = new byte[64];
stream.BeginRead(buffer, 0, buffer.Length, new AsyncCallback(OnRead), buffer);
client.Close();
Console.ReadKey();
}
catch (Exception)
{
//...
}
}
void OnRead(IAsyncResult result)
{
try
{
stream.EndRead(result);
byte[] buffer = result.AsyncState as byte[];
if (buffer != null)
{
//...
}
// continue to read the next 64 bytes
buffer = new byte[64];
stream.BeginRead(buffer, 0, buffer.Length, new AsyncCallback(OnRead), buffer);
}
catch (Exception)
{
// From here you can get exceptions thrown during the asynchronous read
}
}
}
}
- 为了避免阻塞,只在DataAvailable为true时调用Read()
- ThreadPool不适合长时间运行的任务,所以重构while循环
- 在读取之前关闭连接(因为工作项是异步执行的)
这可能有助于
void Run() {
ThreadPool.QueueUserWorkItem(ReadLoop);
}
void ReadLoop(object x) {
if (stream.DataAvailable)
stream.Read(new byte[64], 0, 64);
else
Thread.Sleep(TimeSpan.FromMilliseconds(200));
if (Finished)
client.Close();
else if (!Disposed && !Finished)
ThreadPool.QueueUserWorkItem(ReadLoop);
}
您需要管理Finished&在你真正的课堂上表现得很好。
如果实现了简单的控制台客户端应用程序,那么为什么要使用另一个线程来连接并从服务器接收数据?
static void Main(string[] args)
{
var client = new TcpClient("...", ...);
var buffer = new byte[1024];
using (var networkStream = client.GetStream())
{
int bytesRead;
while ((bytesRead = networkStream.Read(buffer, 0, buffer.Length)) > 0)
{
var hexString = BitConverter.ToString(buffer, 0, bytesRead);
Console.WriteLine("Bytes received: {0}", hexString);
}
}
}