IPhone : How to create a TCP Server on the iPhone?

on Sunday, March 29, 2015

I want to create a TCP server on the iPhone. I tried to write this server using Apple's developer help, but I had no success. I tried to listen with CoreFoundation and with POSIX Socket API but none of these worked.


Using CoreFoundation I implemented the following:



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];


Using the POSIX Socket API I implemented this:



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);


But then I didn't know how to handle the events with Grand Central Dispatch.


When I try to connect with some client I always get the exception "Connection refused" on client side.


Does anybody have some example code?


0 comments:

Post a Comment