Created
February 2, 2019 14:38
-
-
Save lorenzoferrante/18203a52347777e69483cff64f452758 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
void ListeningSocketCallback(CFSocketRef sock, | |
CFSocketCallBackType type, CFDataRef address, const void *data, | |
void *info) | |
{ | |
int fd = * (const int *) data; | |
CFReadStreamRef readStream; | |
CFWriteStreamRef writeStream; | |
NSInputStream * inputStream; | |
NSOutputStream * outputStream; | |
CFStreamCreatePairWithSocket(NULL, fd, &readStream, | |
&writeStream); | |
inputStream = [NSMakeCollectable(readStream ) autorelease]; | |
outputStream = [NSMakeCollectable(writeStream) autorelease]; | |
[inputStream setProperty:(id)kCFBooleanTrue | |
forKey:(NSString *)kCFStreamPropertyShouldCloseNativeSocket]; | |
} | |
- (void)createSocket { | |
int fd4; | |
struct sockaddr_in sin; | |
fd4 = socket(AF_INET, SOCK_STREAM, 0); | |
memset(&sin, 0, sizeof(sin)); | |
sin.sin_family = AF_INET; | |
sin.sin_len = sizeof(sin); | |
sin.sin_port = 0; | |
int err = bind(fd4, (const struct sockaddr *) &sin, sin.sin_len); | |
socklen_t addrLen = sizeof(sin); | |
err = getsockname(fd4, (struct sockaddr *) &sin, &addrLen); | |
err = listen(fd4, 5); | |
CFSocketContext context = {0, NULL, NULL, NULL, NULL}; | |
CFSocketRef sock; | |
CFRunLoopSourceRef rls; | |
sock = CFSocketCreateWithNative(NULL, | |
fd4, | |
kCFSocketAcceptCallBack, | |
ListeningSocketCallback, | |
&context); | |
rls = CFSocketCreateRunLoopSource(NULL, sock, 0); | |
CFRunLoopAddSource(CFRunLoopGetCurrent(), | |
rls, | |
kCFRunLoopCommonModes); | |
CFRelease(rls); | |
CFRelease(sock); | |
NSNetService *service = [[NSNetService alloc] | |
initWithDomain:@"" | |
type:@"_http._tcp." | |
name:@"" | |
port:ntohs(sin.sin_port)]; | |
myService = service; | |
self.port = sin.sin_port; | |
[service scheduleInRunLoop: [NSRunLoop currentRunLoop] | |
forMode: NSRunLoopCommonModes]; | |
[service setDelegate: self]; | |
[service publish]; | |
isRunning = YES; | |
NSMutableDictionary *txtDict = [NSMutableDictionary dictionaryWithCapacity:2]; | |
[txtDict setObject:@"moo" forKey:@"cow"]; | |
[txtDict setObject:@"quack" forKey:@"duck"]; | |
[self sendTxtData:service withDict:txtDict]; | |
} | |
- (void)sendTxtData:(NSNetService *)service withDict:(NSMutableDictionary *)dict { | |
NSData *txtData = [NSNetService dataFromTXTRecordDictionary:dict]; | |
[service setTXTRecordData:txtData]; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment