Mac版socketサーバ、GCDAsyncSocket、データ転送、メッセージソース、コンテンツ展示、オンラインユーザー数統計

5731 ワード

この間、携帯電話端末のソケット通信を書きました.テストが必要なので、「GcDAsyncSocket」で一時的にソケットサーバーを書いて、自分のソケット通信をテストすることができます.
Magic.gif
demoアドレス:https://github.com/joymakee/macSocketServer.git
主な機能は以下の通りです.
SOcketデータをテストするためのmacサーバapp
1.アプリケーションを開くと、自機ipが自動的に取得され、ポートのデフォルト8080が表示されます.
2.「監視開始」をクリックし、ポート8080のデータ傍受を行う
3.サーバがデータを受信するとソースアドレス、ポートおよびデータ内容が表示され、複数のsocketが本サーバに接続されている場合、a,b,cのようなデータ転送が行われ、aがサーバにデータを転送すると、サーバはデータをb,cに転送し、同じbがデータを送信するとa,cも受信できる
//.h 
#import 
@class GCDAsyncSocket;
typedef void (^SocketBlock)(GCDAsyncSocket *client,NSString *message);

@interface SerViceAPP : NSObject

+ (instancetype)shareInstance;

-(void)openSerVice;

- (void)closeService;

@property (nonatomic,copy) SocketBlock messageBlock;
@end
//.m 
#import "SerViceAPP.h"
#import "GCDAsyncSocket.h"
#import "GCDAsyncSocket+category.h"

@interface SerViceAPP()
@property(nonatomic, strong)GCDAsyncSocket *serve;
@property(nonatomic, strong)NSMutableArray *socketConnectsM;
@property(nonatomic, strong)NSThread *checkThread;
@end
static SerViceAPP *instance;
@implementation SerViceAPP
+ (instancetype)shareInstance{
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        instance = [[super alloc] init];
    });
    return instance;
}
-(NSThread *)checkThread{
    return _checkThread = _checkThread?:[[NSThread alloc]initWithTarget:self selector:@selector(checkClientOnline) object:nil];
}
-(GCDAsyncSocket *)serve{
    if (!_serve) {
        _serve = [[GCDAsyncSocket alloc] initWithDelegate:self delegateQueue:dispatch_get_global_queue(0, 0)];
        _serve.delegate = self;
    }
    return _serve;
}
-(NSMutableArray *)socketConnectsM{
    return _socketConnectsM= _socketConnectsM?:[NSMutableArray array];
}
-(void)openSerVice{
    NSError *error;
    if (self.serve.isDisconnected) {
        [self.checkThread start];
        BOOL sucess = [self.serve acceptOnPort:8088 error:&error];
        NSLog(sucess?@" , ...":@" ...");
    }
}
- (void)closeService{
    if (!self.checkThread.isCancelled) {
        [self.checkThread cancel];
    }
    if (self.serve.isConnected) {
        @synchronized (_serve) {
            [self.serve disconnect];
        }
    }
}
#pragma delegate
- (void)socket:(GCDAsyncSocket *)serveSock didAcceptNewSocket:(GCDAsyncSocket *)clientSocket{
    //   socket 
    NSLog(@"%@ IP: %@: %zd  ...",clientSocket,clientSocket.connectedHost,clientSocket.connectedPort);
    // 1. socket 
    clientSocket.timeNew = [NSDate date];
    [self.socketConnectsM addObject:clientSocket];
    [clientSocket readDataWithTimeout:-1 tag:0];
}
- (void)socket:(GCDAsyncSocket *)clientSocket didReadData:(NSData *)data withTag:(long)tag  {
    // 
    NSString *clientStr = [[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding];
    ![clientStr isEqualToString:@"heart"] && clientStr.length!=0 &&self.messageBlock?self.messageBlock(clientSocket,clientStr):nil;
    for (GCDAsyncSocket *socket in self.socketConnectsM) {
         if (![clientSocket isEqual:socket]) {
             //   
             if(![clientStr isEqualToString:@"heart"] && clientStr.length!=0)
             {
                 [self writeDataWithSocket:socket str:clientStr];
             }
         }
         else{socket.timeNew = [NSDate date];}
    }
    [clientSocket readDataWithTimeout:-1 tag:0];
}
- (void)socketDidDisconnect:(GCDAsyncSocket *)sock withError:(NSError *)err{
    //  , , 
    NSLog(@" ");
    [self.socketConnectsM enumerateObjectsUsingBlock:^(GCDAsyncSocket *client, NSUInteger idx, BOOL * _Nonnull stop) {
        if([client isEqual:sock]){
            [self.socketConnectsM removeObject:client];
            *stop = YES;
        }
    }];
}
-(void)exitWithSocket:(GCDAsyncSocket *)clientSocket{
    [self writeDataWithSocket:clientSocket str:@" 
"]; [self.socketConnectsM enumerateObjectsUsingBlock:^(GCDAsyncSocket *client, NSUInteger idx, BOOL * _Nonnull stop) { if([client isEqual:clientSocket]){ [self.socketConnectsM removeObject:client]; *stop = YES; } }]; NSLog(@" :%ld",self.socketConnectsM.count); }
- (void)socket:(GCDAsyncSocket *)sock didWriteDataWithTag:(long)tag{
    NSLog(@" ..");
}
- (void)writeDataWithSocket:(GCDAsyncSocket*)clientSocket str:(NSString*)str{
    [clientSocket writeData:[str dataUsingEncoding:NSUTF8StringEncoding] withTimeout:-1 tag:0];
}
#pragma checkTimeThread
//   runloop  socket time
- (void)checkClientOnline{
    @autoreleasepool {
        [NSTimer scheduledTimerWithTimeInterval:35 target:self selector:@selector(repeatCheckClinetOnline) userInfo:nil repeats:YES];
        [[NSRunLoop currentRunLoop]run];
    }
}
//    client
- (void)repeatCheckClinetOnline{
    if (self.socketConnectsM.count == 0) {
        return;
    }
    NSDate *date = [NSDate date];
    NSMutableArray *arrayNew = [NSMutableArray array];
    for (GCDAsyncSocket *socket in self.socketConnectsM ) {
        if ([date timeIntervalSinceDate:socket.timeNew]>30) {
            continue;
        }
        [arrayNew addObject:socket   ];
    }
    self.socketConnectsM = arrayNew;
}

クライアントはこれとあまり差がありません