接收端socket
1.初始化接收端socket對象spa
receiveSocket = [[AsyncUdpSocket alloc] initWithDelegate:self];3d
2.綁定端口orm
[receiveSocket bindToPort:6478 error:nil];對象
3.監聽接收數據ip
[receiveSocket receiveWithTimeout:-1 tag:10];it
發送端coding
1.初始化發送端socket對象方法
sendSocket = [[AsyncUdpSocket alloc] initWithDelegate:self];im
//發送數據
[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;
}