C# 關閉UDP時如何處理?

bb_chen 2008-11-20 08:43:55
我在點擊一個按鈕時,會彈出一個窗體Form2,
private void Form2_Load(object sender, EventArgs e)
{
GlobalUDP.UDPClient = new UdpClient();
GlobalUDP.EP = new IPEndPoint(IPAddress.Parse("255.255.255.255"), 26868);

IPEndPoint BindEP = new IPEndPoint(IPAddress.Any, 26868);
byte[] DiscoverMsg = Encoding.ASCII.GetBytes("Discovery:Who is out there?");

GlobalUDP.UDPClient.Client.Bind(BindEP);
GlobalUDP.UDPClient.MulticastLoopback = false;
GlobalUDP.UDPClient.EnableBroadcast = true;

//Configure ourself to receive discovery responses
GlobalUDP.UDPClient.BeginReceive(ReceiveCallback, GlobalUDP);

// Transmit the discovery request message
GlobalUDP.UDPClient.Send(DiscoverMsg, DiscoverMsg.Length, new System.Net.IPEndPoint(System.Net.IPAddress.Parse("255.255.255.255"), 26868));
}

當關閉Form2窗體,並再次點開Form2窗體時,會出現如下錯誤:
Only one usage of each socket address (protocol/network address/port) is normally permitted

請教:應該在關閉窗體時如何處理?
...全文
175 9 打赏 收藏 转发到动态 举报
写回复
用AI写文章
9 条回复
切换为时间正序
请发表友善的回复…
发表回复
baichangle 2012-02-09
  • 打赏
  • 举报
回复
GlobalUDP.UDPClient.Client.Disconnect(true);
bb_chen 2008-11-28
  • 打赏
  • 举报
回复
UP
bb_chen 2008-11-25
  • 打赏
  • 举报
回复
UP
bb_chen 2008-11-20
  • 打赏
  • 举报
回复
 private void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
try
{
//GlobalUDP.EP = null;
if (GlobalUDP.UDPClient.Client != null)
{
GlobalUDP.UDPClient.Client.Shutdown(System.Net.Sockets.SocketShutdown.Both);
GlobalUDP.UDPClient.Client.Disconnect(false);
GlobalUDP.UDPClient.Close();
}
}
catch
{ }
}


上面代碼為關閉窗體時釋放了資源。
但是這樣在再開窗體時,會出現下面這個錯誤:
A request to send or receive data was disallowed because the socket had already been shut down in that direction with a previous shutdown call
zlkingdom 2008-11-20
  • 打赏
  • 举报
回复
在你关闭窗体时要把资源释放完
bb_chen 2008-11-20
  • 打赏
  • 举报
回复
HELP
bb_chen 2008-11-20
  • 打赏
  • 举报
回复
HELP
shily_fly 2008-11-20
  • 打赏
  • 举报
回复
关注,UP上去
bb_chen 2008-11-20
  • 打赏
  • 举报
回复
UP

111,130

社区成员

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

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

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