UDP的使用

//

//  该类管理所有的UDP发送

#import <Foundation/Foundation.h>

#import "AsyncUdpSocket.h"

@protocolUDPManagerDelegate;

#define fromHostKey @"fromHost"

#define dataKey @"data"

#define socketTypeKey @"socketType"

#define errorTypeKey @"error"

typedefenum{

    NewDevice=0x01,//设备发现

    AddDevice=0x02,//添加设备

    ControlDevice=0x11,//控制设备

//    TimeQuery=0xFD,//查询定时状态

}SocketNotificationType;

@interface UDPManager : NSObject

{

     AsyncUdpSocket *udpSocket;

   

}

+(UDPManager *)instance;

@property(nonatomic,strong) id<UDPManagerDelegate>myDelegate;

//发送UDP信息 isBroadcast为发送的消息是否为广播类型

-(void)sendToUDPServer:(NSData*) msg address:(NSString*)address port:(int)port isBroadcast:(BOOL)isBoradcast;

//关闭Socket

-(void)closeSocket;

@end

@protocol UDPManagerDelegate <NSObject>

//成功接收消息

-(void)UDPManager:(UDPManager *)udpManager didReceiveData:(NSData *)data fromHost:(NSString *)host socketDataType:(SocketNotificationType)type;

//UDP发送或接收失败

-(void)UDPManagerReceive:(UDPManager *)udpManager error:(NSError *)error;

@end

//

//  UDPManager.m

//  SmartHomeWIFI

//

//  Created by 深圳市 秀软科技有限公司 on 14-2-12.

//  Copyright (c) 2014 huhuaxiang. All rights reserved.

//

//wifi获取网路数据

#import "UDPManager.h"

#import "ByteUnit.h"

#define timerOut 5

static UDPManager *udpManager;

@implementation UDPManager

@synthesize myDelegate;

+(UDPManager *)instance

{

    if(!udpManager)

        udpManager=[[UDPManageralloc]init];

    returnudpManager;

}

-(id)init

{

    if(self=[superinit])

    {

        udpSocket=[[AsyncUdpSocketalloc]initWithDelegate:self];

        [udpSocket bindToPort:36666 error:nil];

    }

    returnself;

}

-(void)dealloc

{

    NSLog(@"UDPManager dealloc");

}

-(void)closeSocket

{

    [udpSocketclose];

    udpSocket=nil;

    udpManager=nil;

}

-(void)sendToUDPServer:(NSData*) msg address:(NSString*)address port:(int)port isBroadcast:(BOOL)isBoradcast{

    NSLog(@"address:%@,port:%d,msg:%@",address,port,msg);

    //receiveWithTimeout is necessary or you won't receive anything

//    [udpSocket receiveWithTimeout:10 tag:0]; //设置超时10

    //命令标示

    unsignedlong mlflag = [ByteUnitsubDataLength:msg startCount:0lenghtCount:1];

    SocketNotificationType type=[selfgetTagType:mlflag];

    [udpSocketreceiveWithTimeout:timerOuttag:0]; //设置超时10

    [udpSocketenableBroadcast:isBoradcast error:nil]; //如果你发送广播,这里必须先enableBroadcast

    [udpSocket sendData:msg toHost:address port:port withTimeout:timerOut tag:type]; //发送udp

}

- (BOOL)onUdpSocket:(AsyncUdpSocket *)sock didReceiveData:(NSData *)data withTag:(long)tag fromHost:(NSString *)host port:(UInt16)port

{

//    NSMutableData *dataMutable=[[NSMutableData alloc]initWithData:data];

    //命令标示

    unsignedlong mlflag = [ByteUnitsubDataLength:data startCount:0lenghtCount:1];

    SocketNotificationType type=[selfgetTagType:mlflag];

    

       NSMutableDictionary *dic=[[NSMutableDictionaryalloc]init];

    [dic setObject:data forKey:dataKey];

    [dic setObject:host forKey:fromHostKey];

    [dic setObject:[NSNumbernumberWithInt:type] forKey:socketTypeKey];

    [[NSNotificationCenterdefaultCenter] postNotificationName:updateSocketNotificationTypeobject:dic];

//    if([myDelegate respondsToSelector:@selector(UDPManager:didReceiveData:fromHost:socketDataType:)])

//        [myDelegate UDPManager:self didReceiveData:data fromHost:host socketDataType:type];

//    [udpSocket receiveWithTimeout:timerOut tag:tag];

    returnYES;

}

-(SocketNotificationType)getTagType:(int)mlflag

{

    SocketNotificationType type;

    switch (mlflag) {//回复类型

        case 0x01://心跳

            type=NewDevice;

            break;

        case 0x02://添加设备

            type=AddDevice;

            break;

        case 0x11://控制设备

            type=ControlDevice;

            break;

//        case 0xFD://查询定时

//            type=TimeQuery;

//            break;

    }

    return type;

}

- (void)onUdpSocket:(AsyncUdpSocket *)sock didNotSendDataWithTag:(long)tag dueToError:(NSError *)error

{

    NSMutableDictionary *dic=[[NSMutableDictionaryalloc]init];

    [dic setObject:[NSNumbernumberWithInt:tag] forKey:errorTypeKey];

    [[NSNotificationCenterdefaultCenter] postNotificationName:updateSocketNotificationTypeobject:dic];

//    if([myDelegate respondsToSelector:@selector(UDPManagerReceive:error:)])

//        [myDelegate UDPManagerReceive:self error:error];

}

- (void)onUdpSocket:(AsyncUdpSocket *)sock didNotReceiveDataWithTag:(long)tag dueToError:(NSError *)error

{

    NSMutableDictionary *dic=[[NSMutableDictionaryalloc]init];

    [dic setObject:[NSNumbernumberWithInt:tag] forKey:errorTypeKey];

    [[NSNotificationCenterdefaultCenter] postNotificationName:updateSocketNotificationTypeobject:dic];

//    if([myDelegate respondsToSelector:@selector(UDPManagerReceive:error:)])

//        [myDelegate UDPManagerReceive:self error:error];

    

    

}

@end

原文地址:https://www.cnblogs.com/alihaiseyao/p/3603933.html