我正在尝试将(POSIX / winsocks)基于套接字的TCP / IP协议的客户端转换为本机Mac OS X框架。在此协议下,在指定端口设置客户端端口,然后将此套接字连接到另一个端口的服务器。基本上(错误检查已删除):
InitCommClient( SOCK *clnt, char *address, unsigned short serverPortNr, unsigned short clientPortNr, int timeOutMS )
{
CreateClient( clnt, clientPortNr );
ConnectToServer( *clnt, serverPortNr, address, timeOutMS );
}
CreateClient(SOCK *s, unsigned short port )
{ int yes=1;
*s = socket( AF_INET, SOCK_STREAM, 0 );
setsockopt( *s, SOL_SOCKET, SO_REUSEADDR, &yes, sizeof(yes) );
// set up lsock - htons(port), AF_INIT
bind( *s, (SOCKADDR*)&lsock, sizeof(SOCKADDR_IN) );
{ int delay_flag = fcntl(*s, F_GETFL, 0);
delay_flag |= O_NONBLOCK;
fcntl( *s, F_SETFL, delay_flag );
}
}
CreateServer(SOCK *s, unsigned short port )
{ int yes=1;
*s = socket( AF_INET, SOCK_STREAM, 0 );
// set up lsock - htons(port), AF_INIT
bind( *s, (SOCKADDR*)&lsock, sizeof(SOCKADDR_IN) );
listen( *s, 3 );
{ int delay_flag = fcntl(*s, F_GETFL, 0);
delay_flag |= O_NONBLOCK;
fcntl( *s, F_SETFL, delay_flag );
}
}
ConnectToServer(SOCK s, unsigned short port, const char *address, int timeOutms)
{
// set up fsock - inet_addr(address), htons(port), AF_INET
errSock = connect( s, (SOCKADDR*)&fsock, sizeof(SOCKADDR_IN) );
// handle EINPROGRESS, EWOULDBLOCK, EISCONN and ECONNREFUSED, waiting for socket to become writable
}
当我使用这些功能时,我与在MS Windows上运行的服务器(或在Wine下)获得了有效的连接(虽然看起来我需要以与winsocks相同的方式处理ECONNREFUSED)。
我还可以将创建的套接字传递给CFStreamCreatePairWithSocket以获取功能性NSInputStream,NSOutputStream对:
InitCommClient( &sServer, ipAddress, ServerPortNr, ClientPortNr, 50 );
CFStreamCreatePairWithSocket( NULL, sServer, (CFReadStreamRef*) &nsReadServer, (CFWriteStreamRef*) &nsWriteServer );
是否可以直接创建该对,如果是,如何?目前我只能使用
获得功能性NSInputStreamCFStreamCreatePairWithSocketToHost( NULL, (CFStringRef) [NSString stringWithUTF8String:ipAddress], ServerPortNr,
(CFReadStreamRef*) &nsReadServer, (CFWriteStreamRef*) &nsWriteServer );
使用高级CFStream / NSStream框架是否可能无法使用精细控制(客户端和服务器端口规范,超时规范等)?
答案 0 :(得分:0)
我必须承认它有点(年......),并且对我来说永远不是一个非常优先的问题,而且我的代码还没有看到任何真实的用法。这就是我最终的结果
NSInputStream *nsReadServer = NULL;
NSOutputStream *nsWriteServer = NULL;
void commsInit(const char *ipAddress)
{
InitCommClient( &sServer, ipAddress, ServerPortNr, ClientPortNr, 50 );
if( sServer != NULLSOCKET ){
CFStreamCreatePairWithSocket( NULL, sServer, (CFReadStreamRef*) &nsReadServer, (CFWriteStreamRef*) &nsWriteServer );
[nsReadServer retain]; [nsWriteServer retain];
[nsReadServer setDelegate:[[OurStreamDelegate alloc] init] ];
[nsReadServer scheduleInRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode];
[nsReadServer open]; [nsWriteServer open];
}
}
我看到代码有点混乱,InitCommClient在C ++模块中是什么,但显然它在我进行测试之前运行得很好。
希望这会有所帮助 - 并随意挖掘full code。