我正在尝试在ObjectiveC / iOS上实现一个简单的TCP服务器。最小的示例归结为以下内容:服务器应保持多个TCP连接。每当读取数据(4个字节)时,服务器应回复该连接上的答案(4个字节)。
我首先创建套接字侦听器并在CFRunLoop中安排它:
CFSocketRef initialCfSock = CFSocketCreate(
kCFAllocatorDefault,
PF_INET,
SOCK_STREAM,
IPPROTO_TCP,
kCFSocketAcceptCallBack,
&handleConnect,
NULL);
if( ! initialCfSock ) return;
int yes=1;
setsockopt(CFSocketGetNative(initialCfSock), SOL_SOCKET, SO_REUSEADDR, (void *)&yes, sizeof(yes));
struct sockaddr_in sin = {0};
sin.sin_len = sizeof(sin);
sin.sin_family = AF_INET;
sin.sin_port = htons(50000);
sin.sin_addr.s_addr= htonl(INADDR_ANY);
CFDataRef sincfd = CFDataCreate(
kCFAllocatorDefault,
(UInt8 *)&sin,
sizeof(sin));
if (kCFSocketSuccess != CFSocketSetAddress(initialCfSock, sincfd)) return;
CFRelease(sincfd);
CFRunLoopSourceRef socketsource = CFSocketCreateRunLoopSource(
kCFAllocatorDefault,
initialCfSock,
0);
CFRunLoopAddSource(
CFRunLoopGetCurrent(),
socketsource,
kCFRunLoopCommonModes);
CFRelease(socketsource);
CFRunLoopRun();
然后,在传入连接上,调用连接处理程序(这可以):
NSInputStream * inputStream = NULL; // global variable
NSOutputStream * inputStream = NULL; // global variable
void handleConnect (CFSocketRef s, CFSocketCallBackType callbackType, CFDataRef address, const void *data, void *info)
{
NSLog(@"handleConnect");
CFSocketNativeHandle socketHandle = *(CFSocketNativeHandle *) data;
CFReadStreamRef currentInputStream = NULL;
CFWriteStreamRef currentOutputStream = NULL;
CFStreamCreatePairWithSocket(kCFAllocatorDefault, socketHandle, (CFReadStreamRef *) ¤tInputStream, (CFWriteStreamRef *) ¤tOutputStream);
if (! currentInputStream || ! currentOutputStream)
return;
// runloop registration
CFStreamClientContext myContext = {
0,
NULL,
NULL,
NULL
};
CFOptionFlags registeredEventsInput = kCFStreamEventHasBytesAvailable | kCFStreamEventErrorOccurred | kCFStreamEventEndEncountered;
if (! CFReadStreamSetClient(currentInputStream, registeredEventsInput, handleInput, &myContext))
return;
CFReadStreamScheduleWithRunLoop(currentInputStream, CFRunLoopGetMain(), kCFRunLoopCommonModes);
CFOptionFlags registeredEventsOutput = kCFStreamEventErrorOccurred | kCFStreamEventEndEncountered;
if (! CFWriteStreamSetClient(currentOutputStream, registeredEventsOutput, handleOutput, &myContext))
return;
CFWriteStreamScheduleWithRunLoop(currentOutputStream, CFRunLoopGetMain(), kCFRunLoopCommonModes);
if (!CFReadStreamOpen(currentInputStream))
return;
if (!CFWriteStreamOpen(currentOutputStream))
return;
inputStream = (NSInputStream *)currentInputStream;
outputStream = (NSOutputStream *)currentOutputStream;
NSLog(@"handleConnect: inputStream=%p, outputStream=%p", currentInputStream, currentOutputStream);
// 2)
}
最后,在传入的字节上,调用输入处理程序。读取四个字节并发送一个四字节的回复:
void handleInput(CFReadStreamRef currentInputStream, CFStreamEventType event, void *clientCallbackInfo)
{
NSLog(@"handleInput: inputStream=%p, outputStream=%p", inputStream, outputStream);
switch(event) {
case kCFStreamEventHasBytesAvailable:
{
// 1) begin
unsigned int a;
NSLog(@"before read: %d/%d, spaceAvail %d, bytesAvail %d", [inputStream streamStatus], [outputStream streamStatus], [outputStream hasSpaceAvailable], [inputStream hasBytesAvailable]);
int err = [inputStream read:(uint8_t *)&a maxLength:sizeof(a)];
NSLog(@"after read: %d/%d, spaceAvail %d, bytesAvail %d, err=%d", [inputStream streamStatus], [outputStream streamStatus], [outputStream hasSpaceAvailable], [inputStream hasBytesAvailable], err);
NSLog(@"before write: %d/%d, spaceAvail %d, bytesAvail %d", [inputStream streamStatus], [outputStream streamStatus], [outputStream hasSpaceAvailable], [inputStream hasBytesAvailable]);
err = [outputStream write:(uint8_t *) &a maxLength:sizeof(a)];
NSLog(@"after write: %d/%d, spaceAvail %d, bytesAvail %d, err=%d", [inputStream streamStatus], [outputStream streamStatus], [outputStream hasSpaceAvailable], [inputStream hasBytesAvailable], err);
// 1) end
break;
}
case kCFStreamEventErrorOccurred:
case kCFStreamEventEndEncountered:
default:
Log(@"[PK] handleInput: stream end/error");
break;
}
}
问题是: handleInput期间的[outputStream write:...]调用不会发送字节,而是阻塞并且没有任何反应。客户端同时等待数据。
这是日志:
handleConnect
handleConnect: inputStream=0x15576cb0, outputStream=0x15576ce0
before read: 2/2, spaceAvail 0, bytesAvail 1
after read: 2/2, spaceAvail 0, bytesAvail 1, err=4
before write: 2/2, spaceAvail 0, bytesAvail 0
但是:当我将handleInput标记为1)的行移动到2)时,一切正常。但后来我同步等待数据,我不想这样做。
然后,相应的日志文件如下所示:
handleConnect
handleConnect: inputStream=0x17632d30, outputStream=0x17632310
before read: 2/2, spaceAvail 0, bytesAvail 0
after read: 2/2, spaceAvail 1, bytesAvail 1, err=4
before write: 2/2, spaceAvail 1, bytesAvail 0
after write: 2/2, spaceAvail 1, bytesAvail 0, err=4
这里有什么问题?