开发者

how to send UDP data in Objective C with AsyncUdpSocket?

开发者 https://www.devze.com 2023-02-27 20:05 出处:网络
I\'m trying to send some small data over UDP using the AsyncUdpSocket library. There is a lot of docs for the TCP connection but none for the UDP connection.

I'm trying to send some small data over UDP using the AsyncUdpSocket library. There is a lot of docs for the TCP connection but none for the UDP connection.

I wrote this开发者_如何学JAVA class to send 5 bytes to a remote host but it looks like nothing is actually going to the wire. I'm monitoring the network using wireshark but I see no outgoing packets. The delegate method "didSendDataWithTag" is never called :(

Any ideas what I forgot ?

#import "UDPController.h"

@implementation UDPController

- (id)init
{
    self = [super init];
    if (self) {
        socket = [[AsyncUdpSocket alloc] initWithDelegate:self];
    }
    return self;
}


- (void) sendUDPTest {
    NSLog(@"%s", __PRETTY_FUNCTION__);

    NSString * string = @"R/103";
    NSString * address = @"192.168.1.130";
    UInt16 port = 21001;
    NSData * data = [string dataUsingEncoding:NSUTF8StringEncoding];

    [socket sendData:data toHost:address port:port withTimeout:-1 tag:1];        
}


/**
 * Called when the datagram with the given tag has been sent.
 **/
- (void)onUdpSocket:(AsyncUdpSocket *)sock didSendDataWithTag:(long)tag {
        NSLog(@"%s", __PRETTY_FUNCTION__);
}


- (void)dealloc
{
    [socket release];
    [super dealloc];
}

@end

cheers


The problem here was that this code was not running in an "application loop" and the main was exiting before the AsyncUdpSocket had time to send the packet.

The same code works fine if it's put in an application.

0

精彩评论

暂无评论...
验证码 换一张
取 消