Transmitting a string via UDP using cocoaasyncsocket
I've been teaching myself Objective-C over the past few months; I'm building an iPhone app for my company. I started as (and still am) a complete novice, but until now I have had no problems easily finding answers to all my questions at various locations online.
For the final, and most important, piece of my app, I need to send a simple string to an address/port via UDP when a button is pressed. The string, address, and port are all variables pulled from an object passed to my view controller.
I have been digging around for two days looking at solutions and reading examples, but everything seriously reads like Greek to me. I'm not sure what major hunk of knowledge I seem to have missed out on, but I'm at a total loss. I learned about cocoaasyncsocket
, and how "simple" it is, and it sounds perfect for what I need, but I just can't seem to wrap my mind around it. I'm really hoping someone here can help break it down for me into simple terms.
Here is a snipp开发者_如何学编程et of the code I've been trying, but with no luck. This code is from my viewController
, with AsyncUdpSocket.h
imported:
-(IBAction)udpButtonTwoPressed:(id)sender {
NSData *myData;
myData = [[NSData alloc] initWithData:([selectedObject
valueForKey:@"udpCommandTwo"])];
AsyncUdpSocket *mySocket;
mySocket = [[AsyncUdpSocket alloc] initWithDelegate:self ];
NSError *error = nil;
if (!([mySocket connectToHost:([selectedObject
valueForKey:@"serverIPAddress"]) onPort:([[selectedObject
valueForKey:@"serverPort"] intValue]) error:&error])) {
NSLog(@"Can't Connect Cause: %@", error);
abort();
}
[mySocket close];
[mySocket release];
[myData release];
}
What am I doing wrong here?
There are two things that stand out from your example.
I don't see you writing anything to the socket. Have a look at writeData:withTimeout:tag.
CocoaAsyncSocket is asynchronous so in your example everything is going out of scope. If you are really wanted to write synchronously there is an example in the reference.
NSString *customRunLoopMode = @"MySyncWrite";
[asyncSocket addRunLoopMode:customRunLoopMode]; [asyncSocket writeData:didBackgroundData withTimeout:TIMEOUT_NONE tag:TAG_BG];
syncWriteComplete = NO; BOOL runLoopReady = YES;
while (runLoopReady && !syncWriteComplete) { runLoopReady = [[NSRunLoop currentRunLoop] runMode:customRunLoopMode beforeDate:[NSDate dateWithTimeIntervalSinceNow:1.0]]; }
[asyncSocket removeRunLoopMode:customRunLoopMode];
HTH
精彩评论