CAsysncSocket 之–udp工具–AsyncUdpSocket 用法 . – iPhone手機開發技術文章 iPhone軟體開發教學課程

詳解iPhone 下AsyncSocket網絡庫編程是本文要介紹的內容,iphone的標準推薦CFNetwork C庫編程.但是編程比較煩躁。在其它OS往往用類來封裝的對Socket函數的處理。比如MFC的CAsysncSocket.在iphone也有類似於開源項目.cocoa AsyncSocket庫

官方網站:https://code.google.com/p/cocoaasyncsocket/

這裡隻上例子,自己在項目中使用的,絕對能使用,如果有疑問,歡迎留言討論。

將AsyncUdpSocket.h AsyncUdpSocket.m 導入到你的工程中,

在自己建立的util中,加入一下代碼

[cpp] 
01.<PRE class=cpp name="code">#pragma mark udp 
02.-(void)sendSearchBroadcast{ 
03.    NSString* bchost=@"255.255.255.255"; //這裡發送廣播  
04.    [self sendToUDPServer:@"hello udp" address:bchost port:BCPORT]; 
05.} 
06.-(void)sendToUDPServer:(NSString*) msg address:(NSString*)address port:(int)port{ 
07.    AsyncUdpSocket *udpSocket=[[[AsyncUdpSocket alloc]initWithDelegate:self]autorelease]; //得到udp util  
08.    NSLog(@"address:%@,port:%d,msg:%@",address,port,msg); 
09.    //receiveWithTimeout is necessary or you won't receive anything  
10.    [udpSocket receiveWithTimeout:10 tag:2]; //設置超時10秒  
11.    [udpSocket enableBroadcast:YES error:nil]; //如果你發送廣播,這裡必須先enableBroadcast  
12.    NSData *data=[msg dataUsingEncoding:NSUTF8StringEncoding]; 
13.    [udpSocket sendData:data toHost:address port:port withTimeout:10 tag:1]; //發送udp  
14.}</PRE><PRE class=cpp name="code">//下面是發送的相關回調函數  
15.-(BOOL)onUdpSocket:(AsyncUdpSocket *)sock didReceiveData:(NSData *)data withTag:(long)tag fromHost:(NSString *)host port:(UInt16)port{ 
16.    NSString* rData= [[[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding] 
17.                     autorelease]; 
18.    NSLog(@"onUdpSocket:didReceiveData:—%@",rData);   
19.    return YES; 
20.} 
21.-(void)onUdpSocket:(AsyncUdpSocket *)sock didNotSendDataWithTag:(long)tag dueToError:(NSError *)error{ 
22.    NSLog(@"didNotSendDataWithTag—-"); 
23.     
24.} 
25.-(void)onUdpSocket:(AsyncUdpSocket *)sock didNotReceiveDataWithTag:(long)tag dueToError:(NSError *)error{ 
26.    NSLog(@"didNotReceiveDataWithTag—-"); 
27.} 
28.-(void)onUdpSocket:(AsyncUdpSocket *)sock didSendDataWithTag:(long)tag{ 
29.    NSLog(@"didSendDataWithTag—-"); 
30.} 
31.-(void)onUdpSocketDidClose:(AsyncUdpSocket *)sock{ 
32.    NSLog(@"onUdpSocketDidClose—-"); 
33.}</PRE><BR> 
34.<PRE></PRE> 
35.ok,試一下吧 
36.<P></P> 
37.<P></P> 
38.<PRE></PRE> 
39.<PRE></PRE> 

發佈留言

發佈留言必須填寫的電子郵件地址不會公開。 必填欄位標示為 *