基于udp的socket编程第三方库,需导入头文件 AsycUdpSocket.h
服务器端:
//1.初始化serversocket
AsyncUdpSocket *serverSocket=[[AsyncUdpSocket alloc]initWithDelegate:self];
//2.绑定端口
[serverSocket bindToPort:0x1234 error:nil];
//3.开始监听
[serverSocket receiveWithTimeout:-1 tag:0];
//4.实现代理方法
- (void)onUdpSocket:(AsyncUdpSocket *)sock didSendDataWithTag:(long)tag{
NSLog(@"服务端---发送数据成功");
}
- (void)onUdpSocket:(AsyncUdpSocket *)sock didNotSendDataWithTag:(long)tag dueToError:(NSError *)error{
NSLog(@"服务端--发送数据失败");
}
- (BOOL)onUdpSocket:(AsyncUdpSocket *)sock didReceiveData:(NSData *)data withTag:(long)tag fromHost:(NSString *)host port:(UInt16)port{
NSLog(@"服务端--接收到数据--来自%@:%hu tag:%ld",host,port,tag);
NSString *msg=[[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding];
NSLog(@"消息是:%@",msg);
//默认收到一次就断开,如果想让一直监听,就在下面让它继续监听
[sock receiveWithTimeout:-1 tag:0];
return YES;
}
- (void)onUdpSocket:(AsyncUdpSocket *)sock didNotReceiveDataWithTag:(long)tag dueToError:(NSError *)error{
NSLog(@"服务端--没有接收到数据");
}
- (void)onUdpSocketDidClose:(AsyncUdpSocket *)sock{
NSLog(@"服务端---断开连接");
}
//5.关闭服务端
[serverSocket close];
客户端:
//1.初始化clientsocket
clientSocket=[[AsyncUdpSocket alloc]initWithDelegate:self];
//2.发送消息
NSString *sendMessage=@"这是我发送的消息,哈哈哈哈哈";
NSData *msgData=[sendMessage dataUsingEncoding:NSUTF8StringEncoding];
[clientSocket sendData:msgData toHost:@"192.168.101.182" port:0x1234 withTimeout:5 tag:1];
//3.实现代理方法
- (void)onUdpSocket:(AsyncUdpSocket *)sock didSendDataWithTag:(long)tag{
NSLog(@"客户端---发送数据成功");
}
- (void)onUdpSocket:(AsyncUdpSocket *)sock didNotSendDataWithTag:(long)tag dueToError:(NSError *)error{
NSLog(@"客户端--发送数据失败");
}
- (BOOL)onUdpSocket:(AsyncUdpSocket *)sock didReceiveData:(NSData *)data withTag:(long)tag fromHost:(NSString *)host port:(UInt16)port{
NSLog(@"客户端--接收到数据--来自%@:%hu",host,port);
return YES;
}
- (void)onUdpSocket:(AsyncUdpSocket *)sock didNotReceiveDataWithTag:(long)tag dueToError:(NSError *)error{
NSLog(@"客户端--没有接收到数据");
}
- (void)onUdpSocketDidClose:(AsyncUdpSocket *)sock{
NSLog(@"客户端---断开连接");
}