UDPSocket

简单的UDP

- (void)viewDidLoad
{
    [super viewDidLoad];
    
    //客户端
    _sendSocket = [[AsyncUdpSocket alloc] initWithDelegate:self];
    //绑定一个端口
    [_sendSocket bindToPort:5555 error:nil];
    
    //服务端
    _recvSocket = [[AsyncUdpSocket alloc] initWithDelegate:self];
    //绑定一个端口
    [_recvSocket bindToPort:6666 error:nil];
    
    //服务端等待有没有客户端发送消息
    [_recvSocket receiveWithTimeout:-1 tag:0];
}
//服务端是否接收到了消息
- (BOOL)onUdpSocket:(AsyncUdpSocket *)sock didReceiveData:(NSData *)data withTag:(long)tag fromHost:(NSString *)host port:(UInt16)port{
    
    NSString* str = [[[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding] autorelease];
    _textView.text = [NSString stringWithFormat:@"%@%@:%@\n",_textView.text,host,str];
    
    //继续监听
    [_recvSocket receiveWithTimeout:-1 tag:0];
    
    return YES;
}


//客户端
- (void)sendText:(id)sender{
    NSData* data = [_sendField.text dataUsingEncoding:NSUTF8StringEncoding];
    //发送
    [_sendSocket sendData:data toHost:_ipField.text port:6666 withTimeout:-1 tag:0];
    _textView.text = [NSString stringWithFormat:@"%@我说:%@\n",_textView.text,_sendField.text];
    _sendField.text = @"";
}

//发送后调用
- (void)onUdpSocket:(AsyncUdpSocket *)sock didSendDataWithTag:(long)tag{

}


你可能感兴趣的:(UDPSocket)