【发布时间】:2014-01-16 20:46:56
【问题描述】:
假设我使用 TcpListener 开始监听任何 IP 地址和端口,它是第一次工作。但是在我重新启动程序后不久,我收到了这个错误“每个套接字地址通常只允许使用一次”。听起来我退出程序时没有关闭 tcpListener,我在 Form_closure 中做到了,但没有用。后来我找到了一种通过每次更改端口来解决此问题的方法,尽管这可以解决问题,但我需要一个修复端口。我的代码如下所示。
TcpListener tcpListener;
Socket socketClient;
const int PORT_LISTEN_SERVER = 7568;
tcpListener = new TcpListener(IPAddress.Any, PORT_LISTEN_SERVER);
tcpListener.Start(); //Error at this line
socketClient = tcpListener.AcceptSocket();
IPEndPoint ipend = (IPEndPoint)socketClient.RemoteEndPoint;
toolStripLabel1.Text = "Connection from " + IPAddress.Parse(ipend.Address.ToString());
我如何关闭我的监听器连接
try
{
MessageBox.Show("Try to clean up!");
tcpListener.Stop();
socketClient.Close();
}
catch { MessageBox.Show("Error CleanUp!"); }
更新: 假设我改成函数make recursion。检查也许 tcpListener 的 stop 方法可以解决这个问题。每次我尝试运行该功能时,我都会不断收到错误消息。看来 stop 方法无法解决这个问题。
private void BeginListen()
{
try
{
tcpListener = new TcpListener(IPAddress.Any, PORT_LISTEN_SERVER);
tcpListener.Start();
MessageBox.Show("tcpListener is started");
}
catch (Exception ex)
{
MessageBox.Show("Error at: " + ex);
tcpListener.Stop();
BeginListen();
}
【问题讨论】:
-
你确定你的监听器被关闭了吗? Form.Closing 并不总是触发,这取决于您关闭应用程序的方式。
-
您是否在关闭监听器之前尝试关闭 socketClient?您是否使用
try..catch来查看在尝试关闭套接字/侦听器时是否出错? -
@MichaelEdenfield 我确定我的代码会被执行
-
如果您显示了两条消息,那么您似乎已经找到了问题——您在尝试清理时遇到了异常。你得到了什么例外?
-
@MichaelEdenfield 好吧,我自己解决了。 Socket.Close 在分配给之前执行。
标签: c# sockets tcplistener