CAsysncSocket 之--udp工具--AsyncUdpSocket 用法 .

來源:互聯網
上載者:User

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


官方網站:http://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> 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.