双11狂欢大促

盲盒赢 定制羽绒服

开启惊喜盲盒,抽取你的专属好礼

— 惊喜奖品抢先看 —

网络编程问题

wangren02 wangren02 墨衍会员 · AI 创作全网分发 墨衍智能分发 通过墨衍一键同步至各平台 可同步平台 CSDN微信公众号微博知乎掘金百家号博客园抖音小红书 你的文章也可以这样分发 墨衍会员 ¥399起/年,写一次发全网 我也要 + 加入社区
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”,给出解决的代码,谢谢,没搞过网络编程,很多都不懂,这里很多代码都是抄别人的。
...全文

相关推荐

评论 1
收藏 已收藏
分享
返回顶部
wangren02
C# 111,129 成员 642,540 内容