先建好一個project,將AsyncUdpSocket.h及AsyncUdpSocket.m複製過去。記得加入CFNetwork.framework
這邊有個地方要注意是,AsyncUdpSocket用的是ARC,若專案沒有設定ARC,則要加入編譯條件:
在項目target -> build phases -> compile sources -> AsyncUdpSocket文件後面加入-fobjc-arc,這是為了使編譯器compile-的時候將此文件在arc的條件下編譯。
新增一個要用到的檔案,例如這邊是example
#import <Foundation/Foundation.h>
#import "AsyncUdpSocket.h"
#define DEFAULT_UDP_TIMEOUT 10;
@interface example : NSObject<AsyncUdpSocketDelegate> {
}
-(IBAction)sendData:(id)sender;
@end
#import "example.h"
@interface example() {
AsyncUdpSocket * __udpSocket;
}
- (void)initialSocket;
@end
@implementation example
#DEFAULT_UDP_TIMEOUT 3000.0f
#DEFAULT_UDP_TAG 1
- (id)init
{
self = [super init];
if (self != nil) {Byte *byteArray = (Byte*)malloc(sizeof(Byte)*5);
NSData *data = [NSData dataWithBytes:byteArray length:5];
[self initialSocket:data];
}
return self;
}
-(IBAction)sendData
:(NSData*)data sender:(id)sender{
[__udpSocket sendData:data withTimeout:DEFAULT_UDP_TIMEOUT tag:DEFAULT_UDP_TAG]; //TAG要一樣,才能在同個頻道
}
- (void)initialSocket:(NSData*)data {
//初始化udp packet
__udpSocket = [[AsyncUdpSocket alloc] initWithDelegate:self];
NSError *error = nil;
if (![__udpSocket isConnected]) {
ConfigObject *config = [ConfigObject sharedConfigObject];
NSError *error;
if( [__udpSocket connectToHost:config.ip onPort:config.port error:&error] ) {
CCLOG(@"Ready");
//觸發回應
[self sendData:data sender:nil];
}
else
CCLOG(@"Fail: %@",error);
}
}
//以下是AsyncUdpSocketDelegate的function
#pragma mark udp socket
- (void)onUdpSocket:(AsyncUdpSocket *)sock didSendDataWithTag:(long)tag
{
NSLog(@"data: %@",);
}
- (void)onUdpSocket:(AsyncUdpSocket *)sock didNotSendDataWithTag:(long)tag dueToError:(NSError *)error
{
// You could add checks here
}
- (BOOL)onUdpSocket:(AsyncUdpSocket *)sock
didReceiveData:(NSData *)data
withTag:(long)tag
fromHost:(NSString *)host
port:(UInt16)port
{
// NSString *msg = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
NSLog(@"msg: %@",data);
[__udpSocket receiveWithTimeout:DEFAULT_UDP_TIMEOUT tag:DEFAULT_UDP_TAG];
return YES; //這行一定要有,否則就會到此結束
}
@end
要傳資料就可以用sendData即可
參考網址:
IOS And AsyncUDPSocket - Tutorial?
CocoaAsyncSocket
iPhone 發送UDP廣播並接收資料
iOS AsyncUdpSocket使用简介
iPhone的Socket编程使用开源代码之AsyncSocket
详解iPhone 下AsyncSocket网络库编程
沒有留言:
張貼留言