ViewController.h
@interface ViewController : UIViewController{
CFSocketRef s;
int connectFlag;
}
ViewController.m
void receiveDataCilent(CFSocketRef cs,
CFSocketCallBackType type,
CFDataRef address,
const void *data,
void *info)
{
CFDataRef df = (CFDataRef) data;
int len = CFDataGetLength(df);
if(len <= 0) return;
CFRange range = CFRangeMake(0,len);
UInt8 buffer[len];
NSLog(@"Received %d bytes from socket %d\n",
len, CFSocketGetNative(cs));
CFDataGetBytes(df, range, buffer);
NSLog(@"Client received: %s\n", buffer);
NSLog(@"As UInt8 coding: %@", df);
NSLog(@"len value: %d", len);
}
-(void) clientConnect:(int)sender;{
s = CFSocketCreate(NULL, PF_INET,
SOCK_STREAM, IPPROTO_TCP,
kCFSocketDataCallBack,
receiveDataCilent,
NULL);
struct sockaddr_in sin;
struct hostent *host;
memset(&sin, 0, sizeof(sin));
host = gethostbyname("localhost");
memcpy(&(sin.sin_addr), host->h_addr,host->h_length);
sin.sin_family = AF_INET;
sin.sin_port = htons(6666);
CFDataRef address;
CFRunLoopSourceRef source;
address = CFDataCreate(NULL, (UInt8 *)&sin, sizeof(sin));
CFSocketConnectToAddress(s, address, 0);
CFRelease(address);
source = CFSocketCreateRunLoopSource(NULL, s, 0);
CFRunLoopAddSource(CFRunLoopGetCurrent(),
source,
kCFRunLoopDefaultMode);
CFRelease(source);
CFRunLoopRun();
}
- (void)viewDidLoad
{
[super viewDidLoad];
}
- (void)viewDidAppear:(BOOL)animated {
[super viewDidAppear:animated];
if(connectFlag == 0 ){
[self clientConnect:1];
}
}
First I’m sorry for messing the concept of xcode programming and threading programming I’m very new to xcode and I need to finish my game project soon
This code is suppose to connect to server and waiting for message from server. I try and test it and it work fine. In view I have IBAction that can press and change view.
But after I implement it to my main project. It can run but I cannot press any button or do anything. After log it out. It seem it stuck around CFRunLoopRun(); I think it stuck in loop but why when I test it. it not stuck ?
In my project this code is run from another view not from ViewController like I just test.
I don’t know why it stuck in my project.
Any help would be appreciated.
Don’t run the run loop yourself on the main thread. The main event loop will run it.
Edit: I should say, “within the context of a GUI app”. In a command-line tool, you do need to run the run loop yourself.