2012年8月28日 星期二

2012年8月2日 星期四

iPhone socket sample

client.... #import #include #include #include #include #include #import void dealWithData(CFSocketRef s, CFSocketCallBackType type, CFDataRef address, const void *data, void *info) { /* printf("received %d bytes from socket %d\n", CFDataGetLength((CFDataRef)data), CFSocketGetNative(s)); */ UInt8 buffer[100]; CFDataGetBytes((CFDataRef)data, CFRangeMake(0,CFDataGetLength((CFDataRef)data)),buffer); printf("%s\n",(char*)buffer); } main () { CFSocketRef s = CFSocketCreate(NULL, PF_INET, SOCK_STREAM, IPPROTO_TCP, kCFSocketDataCallBack, dealWithData, NULL); CFDataRef address, data; struct sockaddr_in sin; char message[] = "Insert message to send here.\n"; CFRunLoopSourceRef source; memset(&sin, 0, sizeof(sin)); sin.sin_family = AF_INET; sin.sin_port = htons(8880); address = CFDataCreate(NULL, (char *)&sin, sizeof(sin)); data = CFDataCreate(NULL, message, sizeof(message)); CFSocketConnectToAddress(s, address, 0); CFSocketSendData(s, NULL, data, 0); CFRelease(address); CFRelease(data); source = CFSocketCreateRunLoopSource(NULL, s, 0); CFRunLoopAddSource(CFRunLoopGetCurrent(), source, kCFRunLoopDefaultMode); CFRelease(source); CFRelease(s); CFRunLoopRun(); }