socket udp

基于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(@"客户端---断开连接");

}





转载于:https://my.oschina.net/starmier/blog/203877

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值