2.1.1.先去github上下載 AsyncUdpSocket.h框架包
2.1.2.初始化udp
@interface QCViewController (){ AsyncUdpSocket *asyncUdpSocket;} asyncUdpSocket = [[AsyncUdpSocket alloc] initWithDelegate:self];
2.1.3.綁定端口
NSError *err = nil; [asyncUdpSocket enableBroadcast:YES error:&err]; [asyncUdpSocket bindToPort:9527 error:&err]; //啟動(dòng)接收線程 [asyncUdpSocket receiveWithTimeout:-1 tag:0];
2.1.4.實(shí)現(xiàn)代理方法
//已接收到消息- (BOOL)onUdpSocket:(AsyncUdpSocket *)sock didReceiveData:(NSData *)data withTag:(long)tag fromHost:(NSString *)host port:(UInt16)port{ if(data是找服務(wù)器的){ //根據(jù)客戶端給的IP,利用TCP或UDP 相互連接上就可以開(kāi)始通訊了 } return YES;}//沒(méi)有接受到消息-(void)onUdpSocket:(AsyncUdpSocket *)sock didNotReceiveDataWithTag:(long)tag dueToError:(NSError *)error{}//沒(méi)有發(fā)送出消息-(void)onUdpSocket:(AsyncUdpSocket *)sock didNotSendDataWithTag:(long)tag dueToError:(NSError *)error{ }//已發(fā)送出消息-(void)onUdpSocket:(AsyncUdpSocket *)sock didSendDataWithTag:(long)tag{}//斷開(kāi)連接-(void)onUdpSocketDidClose:(AsyncUdpSocket *)sock{}
注:實(shí)現(xiàn)步驟與服務(wù)器端相似
2.2.1.初始化udp
@interface QCViewController (){ AsyncUdpSocket *asyncUdpSocket;} asyncUdpSocket = [[AsyncUdpSocket alloc] initWithDelegate:self];
2.2.2.綁定端口
NSError *err = nil; [asyncUdpSocket enableBroadcast:YES error:&err]; [asyncUdpSocket bindToPort:9527 error:&err];
2.2.3.實(shí)現(xiàn)代理方法
//已接收到消息- (BOOL)onUdpSocket:(AsyncUdpSocket *)sock didReceiveData:(NSData *)data withTag:(long)tag fromHost:(NSString *)host port:(UInt16)port{ return YES;}//沒(méi)有接受到消息-(void)onUdpSocket:(AsyncUdpSocket *)sock didNotReceiveDataWithTag:(long)tag dueToError:(NSError *)error{}//沒(méi)有發(fā)送出消息-(void)onUdpSocket:(AsyncUdpSocket *)sock didNotSendDataWithTag:(long)tag dueToError:(NSError *)error{ }//已發(fā)送出消息-(void)onUdpSocket:(AsyncUdpSocket *)sock didSendDataWithTag:(long)tag{}//斷開(kāi)連接-(void)onUdpSocketDidClose:(AsyncUdpSocket *)sock{}
2.2.4.廣播尋找
注:廣播iP地址為 255.255.255.255
NSString *str = @"誰(shuí)是服務(wù)器?我的IP是:192.168.80.103"; NSData *data=[str dataUsingEncoding:NSUTF8StringEncoding]; [asyncUdpSocket sendData:data toHost:@"255.255.255.255 port:9527 withTimeout:-1 tag:0];
作者: 清澈Saup
出處: http://www.survivalescaperooms.com/qingche/
本文版權(quán)歸作者和博客園共有,歡迎轉(zhuǎn)載,但必須保留此段聲明,且在文章頁(yè)面明顯位置給出原文連接。
新聞熱點(diǎn)
疑難解答
圖片精選
網(wǎng)友關(guān)注