7

我的 C# .net 应用程序当前执行以下操作(除其他外):

  1. 创建一个在特定端口上打开套接字并等待指令的线程。
  2. 消息进来,套接字线程读取消息并引发事件。
  3. 事件处理程序调用必要的函数来解析消息并执行必要的操作,例如启动应用程序。
  4. 指定的外部“应用程序”异步启动。

当我的应用程序重新启动,但外部应用程序没有关闭时,套接字似乎永远不会关闭。然后,当我再次尝试在该端口上启动通信时,出现错误。但是,只要我关闭外部应用程序,我就可以在该端口上打开一个套接字。

我的程序似乎没有正确关闭。它应该在退出时杀死套接字,但是当外部进程正在运行时,套接字永远不会关闭。

有任何想法吗?

4

4 回答 4

16

This is just a stab because I have seen how you're starting the external process. If you're creating a Process object, my guess is you're not setting:

ProcessStartInfo.UseShellExecute = true;

If UseShellExecute is set to false, the child process will inherit open socket handles from the parent process. This will keep your socket open even if the parent application is closed.

于 2012-04-19T19:26:21.310 回答
1

从我在这里发现的情况来看,我的怀疑可能得到证实,这是新进程从父进程继承句柄的情况,从而导致了您的问题。

看起来您只需从该链接复制/粘贴代码,即可直接调用带有标志集的 Windows CreateProcess API,以免继承句柄。

另一个单独的想法是编写一个中间启动程序,该程序获取命令行信息,然后启动然后退出。这种额外的间接性可能会让您毫不费力地到达您需要的地方。

于 2012-04-19T19:23:34.913 回答
0

您也许可以使用 using 关键字解决此问题

using (Socket socket = new Socket()) {
//The code
}

其他应用程序是否完全使用套接字?

于 2012-04-19T19:15:33.390 回答
0

The first thing is to take a look on the socket state when the application is closed. The socket could be in the TIME_WAIT state that means that it will wait for some time in order to make sure that no other messages will be received. You can read about that here: http://www.isi.edu/touch/pubs/infocomm99/infocomm99-web/ Now the TIME_WAIT state will be generated on the socket according to which of them initiated the connection termination procedure. So if for some reason your socket perform the close action in the server site then in the server site ( in the server's port ) the socket will change the state to the TIME_WAIT, so if you restart your server application during the socket is in TIME_WAIT a new socket will fail to bind to the listening port, I thing that this is the problem you met.

于 2012-04-19T19:25:00.640 回答