Send UDP broadcast and receive data in ios development, and develop udp broadcast in ios
With asyncUdpSocket, the server responds after receiving the broadcast, and then starts communication.
-(Void) init {
AsyncUdpSocket * socket = [[AsyncUdpSocketalloc] initWithDelegate: self];
[SocketlocalPort: 16747];
NSTimeInterval timeout = 5000;
NSString * request = @ "quick_stat ";
NSData * data = [NSDatadataWithData: [request dataUsingEncoding: NSASCIIStringEncoding];
UInt16 port = 8081;
NSError * error;
[Socket enableBroadcast: YESerror: & error];
[Socket sendData: data toHost: @ "commandid 255.255" port: port withTimeout: timeout tag: 1];
[Socket receiveWithTimeout:-1tag: 0];
NSLog (@ "begin scan ");
}
-(BOOL) onUdpSocket :( AsyncUdpSocket *) sock didReceiveData :( NSData *) data withTag :( long) tag fromHost :( NSString *) host port :( UInt16) port {
NSString * result;
Result = [[NSStringalloc] initWithData: data encoding: NSASCIIStringEncoding];
NSLog (@ "% @", result );
NSLog (@ "received ");
}
-(BOOL) onUdpSocket :( AsyncUdpSocket *) sock didNotReceiveDataWithTag :( long) tag dueToError :( NSError *) error {
NSLog (@ "not supported ed ");
}
-(BOOL) onUdpSocket :( AsyncUdpSocket *) sock didNotSendDataWithTag :( long) tag dueToError :( NSError *) error {
NSLog (@ "% @", error );
NSLog (@ "not send ");
}
-(BOOL) onUdpSocket :( AsyncUdpSocket *) sock didSendDataWithTag :( long) tag {
NSLog (@ "send ");
}
-(BOOL) onUdpSocketDidClose :( AsyncUdpSocket *) sock {
NSLog (@ "closed ");
}
Copyright Disclaimer: This article is an original article by the blogger and cannot be reproduced without the permission of the blogger.