標籤:
先匯入:AsyncUdpSocket.h、AsyncUdpSocket.m
添加<AsyncUdpSocketDelegate>協議
建立:@property (nonatomic, strong)AsyncUdpSocket *myUDPSocket;
- (void)viewDidLoad {
[super viewDidLoad];
self.myUDPSocket = [[AsyncUdpSocket alloc]initWithDelegate:self];
//綁定連接埠
[self.myUDPSocket bindToPort:9000 error:nil];
//開啟廣播
[self.myUDPSocket enableBroadcast:YES error:nil];
// 開始接收資料
[self.myUDPSocket receiveWithTimeout:-1 tag:0];
}
-(BOOL)onUdpSocket:(AsyncUdpSocket *)sock didReceiveData:(NSData *)data withTag:(long)tag fromHost:(NSString *)host port:(UInt16)port{
if (![host hasPrefix:@":"]) {
NSString *string = [[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding];
NSLog(@"%@:%@",host,string);
}
[self.myUDPSocket receiveWithTimeout:-1 tag:0];
return YES;
}
- (IBAction)clicked:(id)sender {
[self.myUDPSocket sendData:[@"哈哈哈" dataUsingEncoding:NSUTF8StringEncoding] toHost:@"255.255.255.255" port:9000 withTimeout:-1 tag:0];
}
藍懿教育 UDP Socket