您的位置:首页 > 其它

GCDAsyncUdpSocket 组播监听端口接收数据

2015-06-09 15:14 651 查看
客户端开发一般是发送数据给服务端。这次反过来了,把客户端作为服务端了,监听对应端口并接收数据.

直接上代码:

.......h文件

@interface ListenServerData : NSObject {

}

- (id)initWithData;

@end
........m文件

#import "ListenServerData.h"

#import "GCDAsyncUdpSocket.h"

@interface ListenServerData () {

}

@property (strong, nonatomic) GCDAsyncUdpSocket *gcdUdpSocket;

@end

@implementation ListenServerData

- (id)initWithData;

{

if (self = [super init]) {

self.gcdUdpSocket = [[GCDAsyncUdpSocket alloc] initWithDelegate:selfdelegateQueue:dispatch_get_main_queue()];

NSError *error;

[_gcdUdpSocket bindToPort:88898 error:&error];

if (nil != error) {

NSLog(@"failed.:%@",[error description]);

}

[_gcdUdpSocket enableBroadcast:YES error:&error];

if (nil != error) {

NSLog(@"failed.:%@",[error description]);

}

//组播224.0.0.2地址,如果地址大于224的话,就要设置GCDAsyncUdpSocket的TTL (默认TTL为1)

[_gcdUdpSocket joinMulticastGroup:@"224.0.0.2" error:&error];

if (nil != error) {

NSLog(@"failed.:%@",[error description]);

}

[_gcdUdpSocket beginReceiving:&error];

if (nil != error) {

NSLog(@"failed.:%@",[error description]);

}

}

return self;

}

- (void)dealloc

{

if (_gcdUdpSocket) {

[_gcdUdpSocket close];

}

}

#pragma mark -GCDAsyncUdpsocket Delegate

- (void)udpSocket:(GCDAsyncUdpSocket *)sock didReceiveData:(NSData *)data fromAddress:(NSData *)address withFilterContext:(id)filterContext

{

NSLog(@"Reciv Data len:%d",[data length]);

}

- (void)udpSocketDidClose:(GCDAsyncUdpSocket *)sock withError:(NSError *)error

{

NSLog(@"udpSocketDidClose Error:%@",[error description]);

}

@end
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: