循环TCP服务器

编程入门 行业动态 更新时间:2024-10-18 20:30:34
本文介绍了循环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: // 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服务器

本文发布于:2023-11-15 21:29:35,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1598112.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:服务器   TCP

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!