c - 如果无法获得 websocket 连接则退出应用程序的逻辑

标签 c loops websocket logic exit

我有一个 C 程序,它使用 libwebsockets 打开从客户端到服务器的 websocket。但是,有时网络可能会出现故障。在这种情况下,我在下面编写了一些逻辑,尝试连接 10 次,如果不成功,则应该退出应用程序。逻辑按预期工作,但看起来不太整洁,我确信有更好的方法来做到这一点。对于如何更好地编写此逻辑的评论,我将不胜感激。 exit(-1) 也是退出的正确方法吗?

//Try connect to websocket 10 times or else exit app
 for (int j =0; j < 10; j++) {

         web_socket = lws_client_connect_via_info ( &ccinfo);

          //If you get a connection then exit the for loop
          if(web_socket){
                 break;
          }

      }

   //If you tried 10 times web_socket will be NULL so exit the application
      if(!web_socket) {
          exit(-1);
      }

最佳答案

exit来自 stdlib.h 是最好的方法。从标准开始

Terminates the process normally, performing the regular cleanup for terminating processes.

First, all functions registered by calls to atexit are executed in the reverse order of their registration. Then, all streams are closed and the temporary files deleted, and finally the control is returned to the host environment.

The status argument is returned to the host environment.

我认为代码逻辑很简单,每个人都可以理解。

“我们应该忘记小效率,大约 97% 的情况下:过早的优化是万恶之源。” - Donald E. Knuth

关于c - 如果无法获得 websocket 连接则退出应用程序的逻辑,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45664728/

相关文章:

在 Emacs 中编译并运行 C 程序

c - fread_s 期间结构填充不正确

java - 我想将摩尔斯电码翻译成文字。还有一个小问题

javascript - 如何从 Javascript 设置 WebSocket Origin Header?

javascript - 独立的nodejs客户端连接到自签名的websocket(wss)

websocket - 准备重用需要 Redis/ZeroMQ 后端的 WebSocket 连接服务器

c - 如何改变c中整数中数字的位置

ios - 错误 : ld: warning: ignoring file libfile01. a,文件是为存档而构建的,该存档不是正在链接的架构 (armv7) : libfile01. a

php - 如何使用表单过滤 mysql/php 表数据

javascript - 等到 for-loop 中的所有函数调用结束执行 - Javascript