如何在 iPhone 上创建 TCP 服务器?

How to create a TCP Server on the iPhone?

我想在 iPhone 上创建一个 TCP 服务器。我尝试使用 Apple's developer help 编写此服务器,但没有成功。 我尝试使用 CoreFoundation 和 POSIX Socket API 进行收听,但其中 none 有效。

我使用 CoreFoundation 实现了以下内容:

CFSocketRef myipv4cfsock = CFSocketCreate(kCFAllocatorDefault, PF_INET, SOCK_STREAM, IPPROTO_TCP,
                                          kCFSocketAcceptCallBack, handleConnect, NULL);

struct sockaddr_in mySocket;

memset(&mySocket, 0, sizeof(sin));
mySocket.sin_len = sizeof(sin);
mySocket.sin_family = PF_INET;
mySocket.sin_port = 8000;
mySocket.sin_addr.s_addr= INADDR_ANY;

CFSocketSetAddress(myipv4cfsock, CFDataCreate(kCFAllocatorDefault, (UInt8 *)&mySocket, sizeof(mySocket)));

CFRunLoopSourceRef socketsource = CFSocketCreateRunLoopSource(kCFAllocatorDefault, myipv4cfsock, 0);

CFRunLoopAddSource(CFRunLoopGetCurrent(), socketsource, kCFRunLoopDefaultMode);

CFReadStreamRef readStream;
CFWriteStreamRef writeStream;
CFStringRef remoteHost = CFSTR("localhost");
CFStreamCreatePairWithSocketToHost(NULL, (CFStringRef)remoteHost, 8000, &readStream, &writeStream);

NSInputStream *inputStream = (__bridge_transfer NSInputStream *)readStream;
NSOutputStream *outputStream = (__bridge_transfer NSOutputStream *)writeStream;

[inputStream setDelegate: self];
[outputStream setDelegate: self];
[inputStream scheduleInRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode];
[outputStream scheduleInRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode];
[inputStream open];
[outputStream open];

使用 POSIX 套接字 API 我实现了这个:

int listenSocket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);

struct sockaddr_in socketAddr;
memset(&socketAddr, 0, sizeof(socketAddr));
socketAddr.sin_len = sizeof(sin);
socketAddr.sin_family = AF_INET;
socketAddr.sin_port = 8000;
socketAddr.sin_addr.s_addr= INADDR_ANY;

if (bind(listenSocket, (struct sockaddr *)&socketAddr, sizeof(socketAddr)) < 0)
{
    NSLog(@"Error: Could not bind socket.");
}

listen(listenSocket, 10);

但是后来不知道怎么用Grand Central Dispatch来处理事件。

当我尝试与某些客户端连接时,我总是在客户端收到异常 "Connection refused"。

有人有示例代码吗?

我找到了使用 POSIX 套接字 API 的解决方案。

int listenfd = 0;
struct sockaddr_in serv_addr;

listenfd = socket(AF_INET, SOCK_STREAM, 0);
memset(&serv_addr, '0', sizeof(serv_addr));

serv_addr.sin_family = AF_INET;
serv_addr.sin_addr.s_addr = htonl(INADDR_ANY);
serv_addr.sin_port = htons(8008);

bind(listenfd, (struct sockaddr*)&serv_addr, sizeof(serv_addr));

_listenForConnections = true;
listen(listenfd, 10);

dispatch_async(dispatch_get_global_queue(0, 0), ^{
    NSLog(@"Waiting for connections...");
    while (_listenForConnections)
    {
        __block int connfd = accept(listenfd, (struct sockaddr*)NULL, NULL);
        NSLog(@"Connection accepted");

        char buffer[1024];
        bzero(buffer, 1024);
        NSString *message = @"";
        bool continueReading = true;

        do
        {
            recv(connfd , buffer , 1024 , 0);
            int size = strlen(buffer);
            if ((buffer[size-1] == '}' && buffer[size-2] == '{'))
            {
                continueReading = false;
                buffer[size-2] = '[=10=]';
            }
            message = [NSString stringWithFormat: @"%@%s", message, buffer];
        }while (continueReading);
        NSLog(@"Got message from client");

        char* answer = "Hello World";
        write(connfd, answer, strlen(answer));
    }

    NSLog(@"Stop listening.");
    close(listenfd);
});