你好,我正在为 ios 实现一个纯粹用 c 编写的原始回显服务器。当我进入无限 while 循环以接受传入连接时,就会出现问题。哪里是放置接受循环的最佳位置,并且是无限 while 循环(在我的情况下是我想要的)的最佳实现。
这是流程 在应用程序委托(delegate)内的应用程序函数内设置根 Controller 。 在 Controller 内调用启动服务器函数。 (这个函数永远不会返回)
while(true)
{
@autoreleasepool
{
int exchangeSocket = accept(socket, NULL,NULL);
if(recv(exchangeSocket, buffer, sizeof(buffer), 0) == -1)
{
NSLog(@"%@", @"Error");
}
else
{
//do something with data received
}
}
}
最佳答案
您的方法至少存在两个问题。首先,您不应在主线程上运行无限循环,因为该线程已用于主运行循环。使用您自己的无限循环(无论在何处)阻止此循环将中断事件处理。这就是您的应用程序无法呈现的原因的答案。 reference指定:
Lengthy tasks (or potentially length tasks) should always be performed on a background thread. Any tasks involving network access, file access, or large amounts of data processing should all be performed asynchronously using GCD or operation objects
但是,iOS 确实允许您使用 POSIX 接口(interface)创建线程,例如它提供了 pthread_create 等功能。您应该能够在这样的线程中运行代码,而不会阻塞您的应用程序。
其次,(但也许您不太感兴趣)使用 POSIX 网络 API 有点 discouraged (由于这些 API 无法打开 radio )有利于其他接口(interface)。最接近您喜欢的可能是CFSocket
(也是 C 接口(interface))。
关于iOS 应用程序由于无限 while 循环而无法渲染,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28132921/