无法从传输连接中读取数据: 一个封锁操作被对 WSACancelBlockingCall 的调用中断?
小弟开发的是一个基于tcpclient tcplistener的网络聊天程序,采用了委托/回调的多线程机制,连接服务器均正常,但是当客户端断开连接时,就会产生如题的异常,下面是部分代码:private void ReceiveData()//由请求连接按钮启动的线程
{
while (true)
{
netStream = client.GetStream();
byte[] bytes = new byte[64];
netStream.Read(bytes, 0, bytes.Length);//异常出现地方
string msg = Encoding.UTF8.GetString(bytes);
AddListBoxItem(msg);
}
}
希望大虾帮忙啊 --------------------编程问答-------------------- 请求连接的代码在这里:
private void button1_Click(object sender, EventArgs e)
{
try
{
int port = int.Parse(textBox2.Text);
client = new TcpClient();
IPAddress remoteIP = IPAddress.Parse(textBox1.Text);
client.Connect(remoteIP, port);
statusBar1.Text = "已经连接到服务器";
Thread thread = new Thread(new ThreadStart(ReceiveData));
thread.IsBackground = true;
thread.Start();
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
} --------------------编程问答-------------------- 帮你顶 --------------------编程问答-------------------- 定义的委托:
delegate void AddListBoxItemCallback(string text);
AddListBoxItemCallback listBoxCallback;
public Form1()
{
InitializeComponent();
listBoxCallback = new AddListBoxItemCallback(AddListBoxItem);
}
private void AddListBoxItem(string text)
{
//如果listBoxReceive被不同的线程访问则通过委托处理;
if (listBox1.InvokeRequired)
{
this.Invoke(listBoxCallback, text);
}
else
{
listBox1.Items.Add(text);
listBox1.SelectedIndex = listBox1.Items.Count - 1;
}
}
--------------------编程问答-------------------- ding qi --------------------编程问答-------------------- 自己顶,我知道有点难了,还是希望大虾能现身 --------------------编程问答-------------------- sdfs --------------------编程问答-------------------- 从你的代码上看,可能是客户端关闭时,连接断开了,可是线程并没有立刻停止,所以会显示异常 --------------------编程问答-------------------- private void Form1_Load(object sender, EventArgs e)
{
thread.Abort();
client.Close();
} --------------------编程问答-------------------- 原因大概是客户端关闭socket连接时,服务器这边netStream.Read(bytes, 0, bytes.Length);仍在读取状态。
补充:.NET技术 , C#