网络编程问题

wangren02 2011-09-19 10:27:16
private void Form1_Load(object sender, EventArgs e)
{
Thread myThread = new Thread(new ThreadStart(AcceptConnection));
myThread.Start();


}
private void AcceptConnection()
{
IPAddress[] ip = Dns.GetHostAddresses(Dns.GetHostName());
listener = new TcpListener(ip[0], 23432);
listener.Start();
while (isExit == false)
{
try
{
allDone.Reset();
AsyncCallback callback = new AsyncCallback(AcceptTcpClientCallback);
this.toolStripStatusLabel1.Text= "开始等待连接……";
listener.BeginAcceptTcpClient(callback, listener);
allDone.WaitOne();
}
catch (Exception e)
{
string s = "da";
this.toolStripStatusLabel1.Text = e.Message;
break;
}
}
}

private void AcceptTcpClientCallback(IAsyncResult iar)
{
try
{
allDone.Set();
TcpListener mylistener = (TcpListener)iar.AsyncState;
TcpClient client = mylistener.EndAcceptTcpClient(iar);
this.toolStripStatusLabel1.Text = "已接受客户连接:" + client.Client.RemoteEndPoint;
comboBox1.Invoke(setcomboxcallback, client.Client.RemoteEndPoint.ToString());
DataReadWrite datareadwrite = new DataReadWrite(client);
clientlist.Add(datareadwrite);
//SendString(datareadwrite, "服务器已经接受连接,请通话……");
datareadwrite.ns.BeginRead(datareadwrite.read, 0, datareadwrite.read.Length, ReadCallBack, datareadwrite);
}
catch (Exception e)
{

this.toolStripStatusLabel1.Text = e.Message;
return;
}
}
private void ReadCallBack(IAsyncResult iar)
{
DataReadWrite datareadwrite = (DataReadWrite)iar.AsyncState;
try
{

int recv = datareadwrite.ns.EndRead(iar);
if (recv == 0)
{
this.toolStripStatusLabel1.Text = string.Format("{0}断开连接", datareadwrite.client.Client.RemoteEndPoint.ToString());
this.comboBox1.Invoke(removecomboboxitemscallback, datareadwrite.client.Client.RemoteEndPoint.ToString());
datareadwrite.client.Client.Close();
return;
}

//this.listBoxMsg.Invoke(setlistboxmsgcallback, string.Format("[来自{0}]{1},{2}个字节", datareadwrite.client.Client.RemoteEndPoint, CommandClass.StrHelp(msg).Substring(0, recv * 2), recv));
if (isExit == false)
{
datareadwrite.InitReadArray();
datareadwrite.ns.BeginRead(datareadwrite.read, 0, datareadwrite.read.Length, ReadCallBack, datareadwrite);
}
}
catch (Exception e)
{
this.toolStripStatusLabel1.Text = e.Message;
}
}


客户端能连接上收发信息没问题,但如果客户端断开连接后再重新连接,能连接上,可是一发信息就出问题了:“无法将数据写入传输连接,无法访问已释放的对象,对象名:system.Net.Sockets.Socket”,给出解决的代码,谢谢,没搞过网络编程,很多都不懂,这里很多代码都是抄别人的。
...全文
51 1 打赏 收藏 转发到动态 举报
写回复
用AI写文章
1 条回复
切换为时间正序
请发表友善的回复…
发表回复
hongjiaoli 2011-09-19
  • 打赏
  • 举报
回复
学习了

110,533

社区成员

发帖
与我相关
我的任务
社区描述
.NET技术 C#
社区管理员
  • C#
  • Web++
  • by_封爱
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告

让您成为最强悍的C#开发者

试试用AI创作助手写篇文章吧