网络编程问题
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”,给出解决的代码,谢谢,没搞过网络编程,很多都不懂,这里很多代码都是抄别人的。