循环TCP服务器 [英] Loop TCP Server

查看:65
本文介绍了循环TCP服务器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个已创建的TCP客户端和服务器,如果连接断开,我希望服务器继续尝试连接,直到再次建立连接为止.我在下面提出的代码可以工作大约30秒钟,但随后却给了我一个错误.

I have a TCP client and server that I have created and I would like for the server to keep making connection attempts if the connection is lost, untill the connection is made again. The code i have come up with below works for about 30 seconds but then it give me an error.

private void intial()             
  try
           {

               server = new TcpClient("192.168.1.101";, 808); //and heartbreaks :)
           }
               catch (SocketException)
           {
               intial();
                   return;
           }




该错误显示"System.dll中发生了类型为"System.StackOverflowException"的未处理的异常"

如果有人可以帮助我,我将不胜感激.
预先表示感谢.




The error says "An unhandled exception of type ''System.StackOverflowException'' occurred in System.dll"

If anyone could help me I would greatly appreciate it.
Thanks in advance.

推荐答案

问题是,只要连接尝试失败,您就不断从自身内部调用initial(),而您实际上从未从该函数返回. br/>
发生的情况看起来像这样:

The problem is that you keep calling initial() from within itself whenever a connection attempt fails, and you never actually return from the function.

What happens looks kind of like this:

initial()
  try to connect, fail
  call initial()
    try to connect, fail
    call initial()
      try to connect, fail
      call initial()
        try to connect, fail
        call initial()
          try to connect, fail
          call initial()
            try to connect, fail
            call initial()



最终,您耗尽了堆栈上的空间,并得到了错误.如果您真的想永远尝试连接到该地址,则应使用while循环.但实际上,我看不到您为什么要那样循环,如果当时无法到达目的地,则应用程序将挂起.



Eventually you run out of space on the stack and you get your error. If you really wanted to try forever to connect to the address then you should use a while loop. But really, I can''t see why you would want to loop like that, if the destination was unreachable at the time then the application would just hang.

private void Initial()
{
  server = new TcpClient();
  bool connected = false;
  while(!connected)
  {
    try
    {
      server.Connect("192.168.1.101", 808);
      connected = true;
    }
    catch (SocketException e)
    {
      //Check e.ErrorCode
      //Error codes are at:
      // http://msdn.microsoft.com/en-us/library/ms740668(VS.85).aspx
    }
  }
}



您还应该检查错误代码,因为有很多原因导致连接尝试失败的原因,并且在大多数情况下,您可能希望放弃.



You should also check the error code, because there are quite a few reasons that a connection attempt may fail, and on most of them you would probably want to give up.


这篇关于循环TCP服务器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆