AsyncSocket(简单的实现与服务器的发送消息,接收消息)

来源:互联网 发布:软考程序员百度云 编辑:程序博客网 时间:2024/05/22 10:36

使用cocoapods pod'CocoaAsyncSocket'


1.新建一个NSObject AsyncSocket

#import <Foundation/Foundation.h>

#import "AsyncSocket.h"

enum{

    SocketOfflineByServer,// 服务器掉线,默认为0

    SocketOfflineByUser,  // 用户主动cut

    SocketOfflineByWifiCut,

};

@interface LGSocketServe : NSObject<AsyncSocketDelegate>


+ (LGSocketServe *)sharedSocketServe;

@property (nonatomic,strong)AsyncSocket         *socket;      // socket


@property (nonatomic,retain)NSTimer             *heartTimer;  //心跳计时器

//  socket连接

- (void)startConnectSocket;

// 断开socket连接

-(void)cutOffSocket;

// 发送消息

- (void)sendMessage:(id)message;

@end

2.

#import "LGSocketServe.h"

//自己设定

#define HOST @"服务器地址"

#define PORT 端口号

#import "AsyncSocket.h"

//设置连接超时

#define TIME_OUT 20

//设置写入超时 -1表示不会使用超时

#define WRITE_TIME_OUT -1

//设置读取超时 -1表示不会使用超时

#define READ_TIME_OUT -1


#define MAX_BUFFER 1024


@implementation LGSocketServe


static LGSocketServe *socketServe =nil;


#pragma mark public static methods



+ (LGSocketServe *)sharedSocketServe {

    @synchronized(self) {

        if(socketServe ==nil) {

            socketServe = [[[selfclass]alloc]init];

        }

    }

    returnsocketServe;

}

+(id)allocWithZone:(NSZone *)zone

{

    @synchronized(self)

    {

        if (socketServe ==nil)

        {

            socketServe = [superallocWithZone:zone];

            return socketServe;

        }

    }

    return nil;

}

//建立长连接

- (void)startConnectSocket

{

    self.socket = [[AsyncSocketalloc]initWithDelegate:self];

    [self.socketsetRunLoopModes:[NSArrayarrayWithObject:NSRunLoopCommonModes]];

    if ( ![selfSocketOpen:HOSTport:PORT] )

    {

        

    }

    

}


- (NSInteger)SocketOpen:(NSString*)addr port:(NSInteger)port

{

    

    if (![self.socketisConnected])

    {

        NSError *error = nil;

        [self.socketconnectToHost:addronPort:portwithTimeout:TIME_OUTerror:&error];

    }

    

    return 0;

}

//心跳

- (void)onSocket:(AsyncSocket *)sock didConnectToHost:(NSString *)host port:(UInt16)port{

    //这是异步返回的连接成功,

    NSLog(@"didConnectToHost");

    

    //通过定时器不断发送消息,来检测长连接

    self.heartTimer = [NSTimerscheduledTimerWithTimeInterval:2target:selfselector:@selector(checkLongConnectByServe)userInfo:nilrepeats:YES];

    [self.heartTimerfire];

}


// 心跳连接

-(void)checkLongConnectByServe{

    

    // 向服务器发送固定可是的消息,来检测长连接

    NSString *longConnect = @"connect is here";

    NSData   *data  = [longConnectdataUsingEncoding:NSUTF8StringEncoding];

    [self.socketwriteData:datawithTimeout:1tag:1];

}


//断开用户手动断开连接

-(void)cutOffSocket

{

     self.socket.userData = SocketOfflineByUser;

    [self.socketdisconnect];

}

//重新连接

- (void)onSocketDidDisconnect:(AsyncSocket *)sock

{

    

    NSLog(@"7878 sorry the connect is failure %ld",sock.userData);

    

    if (sock.userData ==SocketOfflineByServer) {

        // 服务器掉线,重连

        [selfstartConnectSocket];

    }

    else if (sock.userData ==SocketOfflineByUser) {

        

        // 如果由用户断开,不进行重连

        return;

    }elseif (sock.userData ==SocketOfflineByWifiCut) {

        

        // wifi断开,不进行重连

        return;

    }

    

}

- (void)sendMessage:(id)message

{

    //像服务器发送数据

    NSData *cmdData = [messagedataUsingEncoding:NSUTF8StringEncoding];

    [self.socketwriteData:cmdDatawithTimeout:WRITE_TIME_OUTtag:1];

}



//发送消息成功之后回调

- (void)onSocket:(AsyncSocket *)sock didWriteDataWithTag:(long)tag

{

    //读取消息

    [self.socketreadDataWithTimeout:-1buffer:nilbufferOffset:0maxLength:MAX_BUFFERtag:0];

}


//接受消息成功之后回调

- (void)onSocket:(AsyncSocket *)sock didReadData:(NSData *)data withTag:(long)tag

{

    //服务端返回消息数据量比较大时,可能分多次返回。所以在读取消息的时候,设置MAX_BUFFER表示每次最多读取多少,当data.length < MAX_BUFFER我们认为有可能是接受完一个完整的消息,然后才解析

    if( data.length <MAX_BUFFER )

    {

        //收到结果解析...

        NSDictionary *dic = [NSJSONSerializationJSONObjectWithData:dataoptions:NSJSONReadingMutableLeaveserror:nil];

        NSLog(@"接收消息:%@",dic);

        //解析出来的消息,可以通过通知、代理、block等传出去

        

    }

    

    

    [self.socketreadDataWithTimeout:READ_TIME_OUTbuffer:nilbufferOffset:0maxLength:MAX_BUFFERtag:0];

}

- (void)onSocket:(AsyncSocket *)sock willDisconnectWithError:(NSError *)err

{

    NSData * unreadData = [sockunreadData];// ** This gets the current buffer

    if(unreadData.length >0) {

        [selfonSocket:sockdidReadData:unreadDatawithTag:0];// ** Return as much data that could be collected

    } else {

        

        NSLog(@" willDisconnectWithError %ld   err = %@",sock.userData,[errdescription]);

        if (err.code ==57) {

            self.socket.userData = SocketOfflineByWifiCut;

        }

    }

    

}

@end

3.viewcontroller里边测试

socketServe = [LGSocketServesharedSocketServe];

    //socket连接前先断开连接以免之前socket连接没有断开导致闪退

    [socketServecutOffSocket];

    socketServe.socket.userData = SocketOfflineByServer;

    [socketServestartConnectSocket];

//发送消息 @"hello world"只是举个列子

    [socketServesendMessage:@"hello world"];


1 0
原创粉丝点击