AsycnSocket not connecting to TCP serial port over wifi - iphone

I have an iPhone app that I run on the simulator. XCode ver 3.2.6/4.3. I am trying to communicate with a radio on a serial port of a PC over wifi, both on the same server... I've tried NSStream and GCDAsyncSocket (just to make sure). The radio has its own IP address and port number. It's actually a TCP/IP wifi module. After changing the remote access on the PC to accept my IP address, I am finally able to connect but I get kicked off immediately, I'm assuming it's when I try to read or write. Same happens when using Telnet, connects then disconnects. The radio issues HELLO when someone connects, so Telnet must try to read since data is sent. I'm guessing. I thought since I am able to connect, I should be able to read/write. (Yes, newbie here)
I would appreciate any thoughts or direction. I've been researching for over a week now and going bonkers.
Thanks. I added the code below as well as the error message.
This is the error message:
socketDidDisconnect:withError: "Error Domain=NSOSStatusErrorDomain
Code=-9844 "The operation couldn’t be completed. (OSStatus error
-9844.)" UserInfo=0x4c38a60 {}"
- (IBAction)performConnection:(id)sender
{
asyncSocket = [[GCDAsyncSocket alloc] initWithDelegate:self delegateQueue:dispatch_get_main_queue()];
NSError *error = nil;
uint16_t port = [[[self serverPort] text] intValue];
if (![asyncSocket connectToHost:[serverAddr text] onPort:port error:&error])
{
DDLogError(#"Unable to connect due to invalid configuration: %#", error);
[self debugPrint:[NSString stringWithFormat:#"Unable to connect due to invalid configuration: %#", error]];
}
else
{
DDLogVerbose(#"Connecting...IP:%#, port:%i", [serverAddr text], port);
}
}
- (void)socket:(GCDAsyncSocket *)sock didConnectToHost:(NSString *)host port:(UInt16)port
{
DDLogInfo(#"socket:%p didConnectToHost:%# port:%hu", sock, host, port);
NSMutableDictionary *settings = [NSMutableDictionary dictionaryWithCapacity:3];
[settings setObject:#"XXX.XXX.X.XXX"
forKey:(NSString *)kCFStreamSSLPeerName];
// In fact, don't even validate the certificate chain
[settings setObject:[NSNumber numberWithBool:NO]
forKey:(NSString *)kCFStreamSSLValidatesCertificateChain];
[settings setObject:(NSString*)kCFStreamPropertySocketSecurityLevel
forKey:(NSString*)kCFStreamSocketSecurityLevelNegotiatedSSL];
DDLogVerbose(#"Starting TLS with settings:\n%#", settings);
[sock startTLS:settings];
[self debugPrint:[NSString stringWithFormat:#"socket:didConnectToHost:%# port:%hu", host, port]];
//[sock readDataToData:[GCDAsyncSocket CRLFData] withTimeout:-1 tag:0];
[sock readDataWithTimeout:-1 tag:0];
}
- (void)socket:(GCDAsyncSocket *)sock didWriteDataWithTag:(long)tag
{
DDLogVerbose(#"socket:didWriteDataWithTag:");
[sock readDataWithTimeout:-1 tag:0];
}
- (void)socket:(GCDAsyncSocket *)sock didReadData:(NSData *)data withTag:(long)tag
{
DDLogVerbose(#"socket:didReadData:withTag:");
NSString *response = [[NSString alloc] initWithData:data encoding:NSASCIIStringEncoding];
NSLog(#"read response:%#", response);
[self debugPrint:[NSString stringWithFormat:#"Read: \n%#",response]];
[response release];
//NSData *newline = [#"\n" dataUsingEncoding:NSASCIIStringEncoding];
//[sock readDataToData:newline withTimeout:-1 tag: 0];
[sock readDataWithTimeout:-1 tag:0];
}
- (IBAction)sendBuf:(id)sender
{
if ([[bufOut text] length] > 0)
{
NSString *requestStr = [NSString stringWithFormat:#"%#\r\n", [bufOut text]];
NSLog(#"Sending:%#",requestStr);
NSData *requestData = [requestStr dataUsingEncoding:NSASCIIStringEncoding];
[asyncSocket writeData:requestData withTimeout:-1.0 tag:0];
[self debugPrint:[NSString stringWithFormat:#"Sent: \n%#",requestStr]];
}
}

I found a partial solution (by sheer accident). It seems the radio or how the radio is setup only allows me to connect/read/write if my app or iMac initiates the connection. It's fine with another PC. Both can initiate a connection and everything works. Still need to resolve this but at least I know my code is working.
Thanks to anyone who gave my problem some thought.

Related

udp didReceiveData receiving two times

I have the problem that I send an udp Message (broadcast) to a client and get an answer, but this will be displayed two times. When I check the communication an my PC with an UDP listener there is only one message.
May be, someone can give me an info how I can resolve this.
I am using a button to start sending the message!
#import "ViewController.h"
#import "GCDAsyncUdpSocket.h"
#interface ViewController ()
{
long tag;
GCDAsyncUdpSocket *udpSocket;
}
#end
#implementation ViewController
- (void)setupSocket
{ udpSocket = [[GCDAsyncUdpSocket alloc] initWithDelegate:self delegateQueue:dispatch_get_main_queue()];
NSError *error = nil;
if (![udpSocket bindToPort:1000 error:&error])
{
NSLog(#"Error binding: %#", error);
return;
}
if (![udpSocket beginReceiving:&error])
{
NSLog(#"Error receiving: %#", error);
return;
}
[udpSocket enableBroadcast:YES error: &error];
NSLog(#"Ready");
}
- (void)viewDidLoad
{
[super viewDidLoad];
if (udpSocket == nil)
{
[self setupSocket];
}
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
- (IBAction)send:(id)sender{
NSString *host = #"192.168.2.255";
if ([host length] == 0)
{
NSLog(#"Address required");
return;
}
NSLog(#"%#",host);
int port = 8888;
NSString *msg = #"1,0,1,2";
NSData *data = [msg dataUsingEncoding:NSUTF8StringEncoding];
[udpSocket sendData:data toHost:host port:port withTimeout:-1 tag:tag];
NSLog(#"SENT (%i): %#", (int)tag, msg);
tag++;
}
- (void)udpSocket:(GCDAsyncUdpSocket *)sock didReceiveData:(NSData *)data
fromAddress:(NSData *)address
withFilterContext:(id)filterContext
{
NSString *msg = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
if (msg)
{
NSLog(#"RECV: %#", msg);
tag++;
NSLog(#"%li",tag);
}
else
{
NSString *host = nil;
uint16_t port = 0;
[GCDAsyncUdpSocket getHost:&host port:&port fromAddress:address];
NSLog(#"RECV: Unknown message from: %#:%hu", host, port);
}
}
#end
Here ist the output!
2013-09-11 09:49:00.132 udptest[5145:907] 15
2013-09-11 09:49:08.218 udptest[5145:907] 192.168.2.255
2013-09-11 09:49:08.220 udptest[5145:907] SENT (15): 1,0,1,2
2013-09-11 09:49:08.319 udptest[5145:907] RECV: 0,0,0,0,0,0,0,0
2013-09-11 09:49:08.321 udptest[5145:907] 17
2013-09-11 09:49:08.323 udptest[5145:907] RECV: 0,0,0,0,0,0,0,0
2013-09-11 09:49:08.324 udptest[5145:907] 18
I would be very grateful if someone could help me.
I have the same strange unwanted and unresolved behaviour: "sender" sends one broadcast UDP message and "receiver" gets two messagges.
I've investigated as much as I could and these are my findings:
1) Wireshark gets only one UDP message.
2) udpSocket:didReceiveData:fromAddress:withFilterContext: gets fired two times!
3) Parsing the "address" param with [GCDAsyncUdpSocket getHost:port:fromAddress:] results in host = ::ffff:192.168.1.118 the FIRST time while host = 192.168.1.118 the SECOND time.
Hope it would be helpful in some manner...
EDIT (with a possible SOLUTION)
The FIRST address (see points 2 and 3) is an actual IPv6 address.
So I guess that the udpSocket:didReceiveData:... is fired two times beacuse the first time the sender is the IPv6 address and the second time the sender is the IPv4 address of the same address.
And so my solution is to enable only the IPv4 in the UDP socket:
[udpSocket setIPv4Enabled:YES];
[udpSocket setIPv6Enabled:NO];
Are the response message and the request message same in terms of what they contain. If yes, then here is one scenario that you might be running into. May be the first packet is the broadcast that you are listening for your self and the second packet is the response. To be more precise, when you send a broadcast (pkt p1), then the sender can also get a copy of p1. Next, when the receiver sends a response (pkt p2), then you see the response as well.
So, how do we verify it. You can look at the senders address (UDP provides an option) and then check if it is your address or the address of the other host.

AsyncSockets - ReadToData - Doesn't work like expected

It's my first specific question here on stackoverflow, cause I couldn't found any helpful solutions for my problem yet.
I need a low level socket connection between my iPhone and OSX Workstation (as TCP Server), to interchange some media data like pictures or audio files. So I think AsyncSockets is a good choise to get this to work. I've often used it for some tiny byte communication.
My Problem is, that I want to use a kind of a header/protocol to tell the server how much data bytes are still in pipe.
A simple communication like "hello world" is working fine, so there are no connection problems.
The mobile device (that wants to send a picture) does the following.
[self setHost:#"172.22.42.207"];
self.socket = [[[AsyncSocket alloc] initWithDelegate:self] autorelease];
NSError *err = nil;
[[self socket] connectToHost:self.host onPort:5009 error:&err];
...
NSData *t = UIImagePNGRepresentation(test);
NSString *header = [NSString stringWithFormat:#"%i", t.length];
NSMutableData *headerData = [[header dataUsingEncoding:NSUTF8StringEncoding] mutableCopy];
[headerData appendBytes:[AsyncSocket CRLFData] length:[[AsyncSocket CRLFData] length]];
[[self socket] writeData:headerData withTimeout:-1 tag:0];
The server is listening that way:
AsyncSocket *s = [[AsyncSocket alloc] initWithDelegate:self];
NSError *err = nil;
[s acceptOnPort:5009 error:&err];
if(err)
NSLog(#"EPIC FAIL...\n%#", err);
....
- (void)onSocket:(AsyncSocket *)sock didAcceptNewSocket:(AsyncSocket *)newSocket
{
NSLog(#"%s", __PRETTY_FUNCTION__);
[newSocket readDataToData:[AsyncSocket CRLFData] withTimeout:-1 tag:0];
}
Now: If I use readData:withTimeout:tag it all works like a charm. But once I change the code to readDataToData:withTimeout:tag, to split the header from the other content, the onSocket:didConnectToHost:port: method is never called. Here are some pretty function logs (I placed them in every delegate method)
Client side:
2012-01-31 13:40:32.962 AVMobile[20643:10703] -[SLViewController onSocket:didConnectToHost:port:]
2012-01-31 13:40:32.964 AVMobile[20643:10703] -[SLViewController onSocket:didWriteDataWithTag:]
Server side:
2012-01-31 13:40:32.961 AVServer[20618:707] -[SLAppDelegate onSocket:didAcceptNewSocket:]
So, next idea... just compare the sending and receiving bytes, so:
Sending: <33333736 35365cba>
Receiving: <33333736 35365cba>
Yeah... now my final question: What am I doing wrong!?
Why isn't it working out for me :)?
Greetings & thanks!
sniperosx
Found a solution:
Just don't use -1 as timeout.
With -1 timeout the AsyncSocket is reading data until the other side is closing the connection, so in this range no delegate method is called.
Cheerz
sniperosx
[Closed]

iphone :client-server communication not occuring

i had made the following programming for client server programming but it is not working. the server is not able to receive the request for connection setup.plz help.
#import "clientserverprogramViewController.h"
#import "secondview.h"
#import <CoreFoundation/CFSocket.h>
#include <sys/socket.h>
#include <netinet/in.h>
NSInputStream *iStream;
NSOutputStream *oStream;
#implementation clientserverprogramViewController
#synthesize name,filepath,display;
-(IBAction) print {
NSString *urlStr = serverIP;]
[display setText : urlStr];
if (![urlStr isEqualToString:#""]) {
NSURL *website = [NSURL URLWithString:urlStr];
if (!website) {
NSLog(#"%# is not a valid URL");
return;
}
NSHost *host = [NSHost hostWithName:[website host]];
[NSStream getStreamsToHost:host port:3000 inputStream:&iStream outputStream:&oStream];
[iStream retain];
[oStream retain];
[iStream setDelegate:self];
[oStream setDelegate:self];
[iStream scheduleInRunLoop:[NSRunLoop currentRunLoop]
forMode:NSDefaultRunLoopMode];
[oStream scheduleInRunLoop:[NSRunLoop currentRunLoop]
forMode:NSDefaultRunLoopMode];
[iStream open];
[oStream open];
}
}
-(IBAction) settings {
[self presentModalViewController:nextview animated: YES];
}
-(IBAction) cancel {
exit(0);
}
- (void)dealloc {
[super dealloc];
}
#end
You only open streams and don't do anything with them. It's like picking up a phone and not dialing a number. Use NSStreamDelegate protocol to implement data transmission code.
Update:
You have these lines that set the delegate for streams:
[iStream setDelegate:self];
[oStream setDelegate:self];
Now implement methods that are defined in NSStreamDelegate protocol in your own class (AFAIK - there's only one of them). See how to receive/send data from there.
Is there a specific reason you're using streams?
What about using NSURLConnection? Here's a piece of code from a project of mine. Both are in KANetworkManager. KANetworkTransactionType is simply a enum that helps me know how to parse the response.
+ (void) createAndStartUrlConnection:(NSMutableURLRequest *)request type:(KANetworkTransactionType)type target:(id)target callback:(SEL)callback;
{
[UIApplication sharedApplication].networkActivityIndicatorVisible = YES;
NSDictionary *requestDict = [NSDictionary dictionaryWithObjectsAndKeys:request, #"request", [NSNumber numberWithInt:type], #"type", target, #"target", [NSValue valueWithPointer:callback], #"callback", nil];
[KANetworkManager performSelectorInBackground:#selector(makeNetworkCall:) withObject:requestDict];
}
I'm able to made a synchronous network call because I always call this method on its own thread. It's a simpler way to achieve asynchronous network communications without dealing with delegates (although the delegate method provides some benefits). Your parseResponse method would need to be specific to whatever your web service it sending back. parseResponse would notify the callback method. Let me know if you have additional questions regarding this.
+ (void) makeNetworkCall:(NSDictionary *)params
{
// We assume this method won't be called from the main thread, so we need our own NSAutoreleasePool.
NSAutoreleasePool *autoreleasePool = [[NSAutoreleasePool alloc] init];
NSMutableURLRequest *request = [params objectForKey:#"request"];
KANetworkTransactionType type = [(NSNumber *)[params objectForKey:#"type"] intValue];
id target = [params objectForKey:#"target"];
SEL callback = (SEL)[[params objectForKey:#"callback"] pointerValue];
NSURLResponse *response;
NSError *err;
// We make a synchronous request assuming we're on a background thread.
NSData *data = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&err];
if (data.length > 0)
{
[self parseResponse:data type:type target:target callback:callback];
}
else
{
NSLog(#"Error occured during network call. %#", err);
}
[autoreleasePool drain];
}
JB gates,
In your code you inform iStream and oStream that your clientserverprogramViewController object is to be the delegate for each. However, a proper delegate needs actual implementation. Your class needs to implement this method:
– stream:handleEvent:
The details are documented here:
Reading From Input Streams
Writing To Output Streams
Also, your code will not work on a real iPhone. There is an updated Core Foundation API for creating the socket pair, details here.
Update
Just wondering if this is not a software issue but maybe the server is behind a firewall. Please give details what the server is, ie webserver, netcat, or simple TCP socket, etc.
Peter

writeData on a syncsocket always blocks on iPhone

I use the asyncsocket sample as a starting point to learn more about wlan communication on iPhone.
On the Mac I start a sample server opening port 0. This works, since I can write data with a test client running on the mac.
On the iPhone I think I managed to connect since "streams connected" returns YES.
Then I would like to send data with a syncsocket: (EDITED VERSION WITH COMPLETE CODE)
import "InterfaceTestAppDelegate.h"
import "InterfaceTestViewController.h"
import "AsyncSocket.h"
import "SyncSocket.h"
#implementation InterfaceTestAppDelegate
#synthesize window;
#synthesize viewController;
(void)onSocket:(AsyncSocket *)sock didConnectToHost:(NSString *)remoteHost port:(UInt16)remotePort
{
NSLog(#"Socket is connected!");
NSLog(#"Remote Address: %#:%hu", remoteHost, remotePort);
NSString *localHost = [sock localHost];
UInt16 localPort = [sock localPort];
NSLog(#"Local Address: %#:%hu", localHost, localPort);
}
(BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
NSLog(#"application:didFinishLaunchingWithOptions:");
/*
asyncSocket = [[AsyncSocket alloc] initWithDelegate:self];
NSError *err = nil;
if (![asyncSocket connectToHost: #"192.168.0.30" onPort: 1234 error: &err])
{
NSLog(#"Error connecting: %#", err);
}
NSData *data = [#"testxyz" dataUsingEncoding:NSUTF8StringEncoding];
NSLog(#"trace 1");
[asyncSocket writeData:data withTimeout:10 tag:0];
NSLog(#"trace 2");
*/
syncSocket = [[SyncSocket alloc] initWithTimeout: 10];
syncSocket.nsLog = YES;
if (![syncSocket connectToHost: #"192.168.0.30" onPort: 12345])
{
NSLog(#"Error connecting syncSocket:");
}
NSData *data = [#"testxyz" dataUsingEncoding:NSUTF8StringEncoding];
NSLog(#"syncSocket trace 1");
[syncSocket writeData:data];
NSLog(#"syncSocket trace 2");
[window addSubview:viewController.view];
[window makeKeyAndVisible];
return YES;
}
It never continues to send the data, the writeData always blocks.
The IP 192.168.0.30 is my Mac's IP. I just used any port 12345 now as you suggested above.
But I don't really know what I have to do on the Mac to receive??
As you can see I actually use syncsocket, then it blocks.
I also tried asyncSocket, then I get the message in the asyncsocket class: writeStream Can NOT Accept Bytes
Maybe its that I don't setup the Mac correctly,ie what app do I need to run on the Mac to test?
Many thank!
For what it's worth, this is specifically how you typically read in some data using AsyncSocket:
-(void)onSocket:(AsyncSocket *)sock
didReadData:(NSData*)data withTag:(long)tag
{
[data getBytes:&getMe length:sizeof(CommProt)];
// now, you must roll in the next read...
[sock readDataToLength:sizeof(CommProt) withTimeout:-1 tag:0];
// CommProt is your communications protocol, so sizeof(CommProt)
// is how much to read at a chunk.
// you can now simply access the fields of getMe,
// for example getMe.x, getMe.y, getMe.latestValue etc etc.
// hope it helps!
}
Of course, you would have previously rolled in the first "primer" read command:
You do that when you connect to a host, hence:
-(void)onSocket:(AsyncSocket *)sock
didConnectToHost:(NSString *)host port:(UInt16)port
{
if ( yourAppSaysItsOkToConnectAtThisMoment == NO )
{
[sock disconnect]; // (so easy, AsyncSockets is a masterpiece)
return;
}
// .. blah blah
// the critical 'primer' read command
[sock readDataToLength:sizeof(CommProt) withTimeout:-1 tag:0];
// .. blah blah
}
Don't forget you must roll in the next read in two places, (a) when you first connect and (b) of course, after each read!
In the example your communications protocol would look like this ...
typedef struct _CommProt // v.3
{
BOOL pressExplosionButton;
BOOL pressFireworksButton;
float usersSteering;
float usersTemperature;
float usersAltitude;
float usersAngle;
}
CommProt;
Variable like "getMe" in the example would simply look like this:
CommProt getMe;
CommProt sendMe;
If you are struggling to understand this type of communications protocol, also try this long answer:
Tablet(iPad/Android)-Server Communication Protocol
AsyncSocket is incredibly beautiful, it was written by the mysterious Justin Voss who seemed to drop off the internet after giving it to the world - it's one of the best libraries ever written, it's a masterpiece.
Hope it helps.

SSDP on the iPhone

I need to be able to send out a UDP message and also receive one in order to discover SSDP devices on the network from the iPhone.
I know that I need to send the packet to the multicast address and my HTTP request needs to look something like this:
M-SEARCH * HTTP/1.1
Host: 239.255.255.250:1900
Man: ssdp:discover
Mx: 3
ST: "urn:schemas-upnp-org:device:InternetGatewayDevice:1"
From reading the docs it appears that I can do all this with CFNetwork and despite reading (and re-reading the docs) I am struggling to get started. Can anyone recommend and tutorials or code snippets to get me over the initial learning hump?
I've got the CFNetwork programming guide:
http://developer.apple.com/mac/library/documentation/Networking/Conceptual/CFNetwork/CFNetwork.pdf
and Beej's Guide to Network programming Using Internet Sockets:
http://beej.us/guide/bgnet/
Thanks
Dave
P.S.
I am unable to use any of the 3rd party libraries and frameworks in this instance.
I have used AsyncUdpSocket successfully to run SSDP Discovery and find controllers. Here are my code snippets:
Initialize and setup the socket:
// AsyncUdpSocket *ssdpSock = [[AsyncUdpSocket alloc] initWithDelegate:self];
AsyncUdpSocket *ssdpSock = [[AsyncUdpSocket alloc] initIPv4];
[ssdpSock setDelegate:self];
Note the first line commented out. I found on the AsyncUdpSocket forums some issues with duplicates. I don't think I was facing them but I did it anyhow.
I added error checking, and it was useful because during my debugging I wasn't closing sockets and I started getting socket setup failures:
NSError *socketError = nil;
if (![ssdpSock bindToPort:1900 error:&socketError]) {
NSLog(#"Failed binding socket: %#", [socketError localizedDescription]);
return statusController;
}
if(![ssdpSock joinMulticastGroup:#"239.255.255.250" error:&socketError]){
NSLog(#"Failed joining multicast group: %#", [socketError localizedDescription]);
return statusController;
}
if (![ssdpSock enableBroadcast:TRUE error:&socketError]){
NSLog(#"Failed enabling broadcast: %#", [socketError localizedDescription]);
return statusController;
}
[ssdpSock sendData:[self.discoverControllerString dataUsingEncoding:NSUTF8StringEncoding]
toHost:#"239.255.255.250"
port:1900
withTimeout:2
tag:1];
Notice the changes I have made to the time out. And then finally did the receive setup, and closed the socket. Note the socket close. Since I am in my own class when I am running this - the code above did not work for me.
[ssdpSock receiveWithTimeout: 2 tag:1];
[NSTimer scheduledTimerWithTimeInterval: 5 target: self
selector:#selector(completeSearch:) userInfo: self repeats: NO];
[ssdpSock closeAfterSendingAndReceiving];
The most important change probably was returning "NO" if I did not find my controller. The first receive was incidentally the discovery message itself coming back. And when I read through the AsyncUdpSocket.h file carefully - returning "NO" when it is not a packet you are looking for helped.
Also note that I am using ARC in my code but I compiled the AsyncUdpSocket without ARC support.
-(void) completeSearch: (NSTimer *)t
{
NSLog(#"%s",__FUNCTION__);
//[ssdpSock close];
//ssdpSock = nil;
}
- (BOOL)onUdpSocket:(AsyncUdpSocket *)sock
didReceiveData:(NSData *)data
withTag:(long)tag
fromHost:(NSString *)host
port:(UInt16)port
{
NSLog(#"%s %ld %# %d",__FUNCTION__,tag,host,port);
NSString *aStr = [[NSString alloc] initWithData:data encoding:NSASCIIStringEncoding];
NSLog(#"%#",aStr);
NSString *compareString = [aStr stringByPaddingToLength:[self.responseString length] withString:#"." startingAtIndex:0];
//NSLog(#"%#", compareString);
//NSLog(#"%#", self.responseString);
if ([compareString isEqualToString:self.responseString])
{
NSLog(#"String Compare, Controller Found!");
[self.controllerList addObject:aStr];
//NSData *controllerIP = [aStr dataUsingEncoding:NSUTF8StringEncoding];
[[NSNotificationCenter defaultCenter] postNotificationName:#"DiscoveredController" object:nil];
return YES;
}
return NO;
}
I have the following code for SSDP search in my app:
-(void)discoverDevices {
ssdpSock = [[AsyncUdpSocket alloc] initWithDelegate:self];
[ssdpSock enableBroadcast:TRUE error:nil];
NSString *str = #"M-SEARCH * HTTP/1.1\r\nHOST: 239.255.255.250:1900\r\nMan: \"ssdp:discover\"\r\nST: mydev\r\n\r\n";
[ssdpSock bindToPort:0 error:nil];
[ssdpSock joinMulticastGroup:#"239.255.255.250" error:nil];
[ssdpSock sendData:[str dataUsingEncoding:NSUTF8StringEncoding]
toHost: #"239.255.255.250" port: 1900 withTimeout:-1 tag:1];
[ssdpSock receiveWithTimeout: -1 tag:1];
[NSTimer scheduledTimerWithTimeInterval: 5 target: self
selector:#selector(completeSearch:) userInfo: self repeats: NO]; }
-(void) completeSearch: (NSTimer *)t {
NSLog(#"%s",__FUNCTION__);
[ssdpSock close];
ssdpSock = nil;}
- (BOOL)onUdpSocket:(AsyncUdpSocket *)sock didReceiveData:(NSData *)data withTag:(long)tag fromHost:(NSString *)host port:(UInt16)port{
NSLog(#"%s %d %# %d",__FUNCTION__,tag,host,port);
NSString *aStr = [[NSString alloc] initWithData:data encoding:NSASCIIStringEncoding];
NSLog(#"%#",aStr);}
It uses the AsyncUdpSocket from CocoaAsyncSocket.
OK, finally done it. Found a class in the public domain (thanks Chris) called AsyncUdpSocket that lets you create a UDP socket which you can then turn on broadcasting and join the multicast address.
There is a nice sendData method, complete with adding to a run loop to prevent blocking.
Hope that helps.
Dave