我有一个已创建的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: // msdn.microsoft/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服务器
发布评论