接收端
1.初始化接收端socket对象
receiveSocket = [[AsyncUdpSocket alloc] initWithDelegate:self];
2.绑定端口
[receiveSocket bindToPort:6478 error:nil];
3.监听接收数据
[receiveSocket receiveWithTimeout:-1 tag:10];
发送端
1.初始化发送端socket对象
sendSocket = [[AsyncUdpSocket alloc] initWithDelegate:self];
//发送数据
[sendSocket sendData:data toHost:ipTF.text port:6478 withTimeout:-1 tag:100];
//协议方法
#pragma mark - AsyncUdpSocketDelegate
//发送数据成功
-(void)onUdpSocket:(AsyncUdpSocket *)sock didSendDataWithTag:(long)tag
{
NSLog(@"发送数据成功!");
}
//接收数据成功
//sock:接收端的socket
//data:接收到的数据
//tag:tag值
//fromHost:发送端的主机ip
//port:端口
-(BOOL)onUdpSocket:(AsyncUdpSocket *)sock didReceiveData:(NSData *)data withTag:(long)tag fromHost:(NSString *)host port:(UInt16)port
{
//接收到的内容
NSString *content = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
//继续监听接收数据(监听一次)
[receiveSocket receiveWithTimeout:-1 tag:10];
return YES;
}