我想通过我的服务器套接字连接套接字库吗?

时间:2016-06-19 07:52:43

标签: ios asp.net objective-c sockets

我正在开发一个由swift和objective c一起编写的套接字基础应用程序。在这个项目中,客户端(Mobile Platform)连接到由asp.net框架编程的服务器套接字。现在,我尝试通过iOS的默认套接字库连接和传输数据(通过输入流和输出流并将它们连接到服务器);但是这个自定义库在特殊情况下无法正常工作。例如,当接收到的数据很大时,我的socket类通过将它们分成2或3部分来获取输入流中的数据,或者当我的应用程序强行退出并且用户在Web面板中执行某些操作,然后再次运行app时,应用程序什么都没有。
所以请给我一个合适的图书馆或指导我解决我的套接字类问题。
请快速帮助我。我有时间.... :(
我应该说它是我的socket类,由Objective c编写!
这是我的套接字类代码:

#import "SocketManage.h"
#import "AppDelegate.h"

@implementation SocketManage
@synthesize inputStream, outputStream,socketOpened;

- (id)init
{
    self = [super init];
    if (self)
    {
        socketOpened=0;
    }//if
    return self;
 }//init

 -(void)openSocket
 {
     DataLayer *dLayer=[[DataLayer alloc]init];
     Setting *setObj=[dLayer getSetting];

     NSString *ip=setObj.serverIP;
     int port=[setObj.serverPort intValue];
     @try
    {
        CFReadStreamRef readStream;
        CFWriteStreamRef writeStream;
        CFStreamCreatePairWithSocketToHost(NULL, (__bridge CFStringRef)ip, port, &readStream, &writeStream);
    NSLog(@"This is ip = %@ and this is port = %d" , ip , port);
    //CFStreamCreatePairWithSocketToHost(kCFAllocatorDefault, (__bridge CFStringRef)ip, port, &readStream, &writeStream);
    //CFReadStreamSetProperty(readStream, kCFStreamPropertyShouldCloseNativeSocket, kCFBooleanTrue);
    //CFWriteStreamSetProperty(writeStream, kCFStreamPropertyShouldCloseNativeSocket, kCFBooleanTrue);
    CFReadStreamSetProperty(readStream, kCFStreamNetworkServiceType, kCFStreamNetworkServiceTypeVoIP);
    CFWriteStreamSetProperty(writeStream, kCFStreamNetworkServiceType, kCFStreamNetworkServiceTypeVoIP);

    inputStream = (__bridge NSInputStream *)readStream;
    outputStream = (__bridge NSOutputStream *)writeStream;
    [inputStream setDelegate:self];
    [outputStream setDelegate:self];
    [inputStream scheduleInRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode];
    [outputStream scheduleInRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode];
    //[inputStream scheduleInRunLoop:[NSRunLoop mainRunLoop] forMode:NSDefaultRunLoopMode];
    //[outputStream scheduleInRunLoop:[NSRunLoop mainRunLoop] forMode:NSDefaultRunLoopMode];
    [inputStream open];
    [outputStream open];

    NSStreamStatus status=[outputStream streamStatus];
    if (status != NSStreamStatusOpen && status != NSStreamStatusOpening && status != NSStreamStatusWriting && status != NSStreamStatusReading)
    {
        [self tryOpenning];
    }//if
}//try
@catch (NSException *exception)
{
    [self tryOpenning];
}//catch
}//openSocket

- (void)stream:(NSStream *)theStream handleEvent:(NSStreamEvent)streamEvent
{
    streamForClose=theStream;
    switch (streamEvent)
    {
        case NSStreamEventHasBytesAvailable:;
            if (theStream == inputStream)
            {
                NSUInteger maxLen=1024;
                uint8_t buffer[maxLen];
                long lenAll=0;
                NSMutableString *total = [[NSMutableString alloc ] init];
                while ([inputStream hasBytesAvailable])
                {
                    long len = [inputStream read:buffer maxLength:maxLen];
                    lenAll+=len;
                    if (len > 0)
                    {
                        NSString *tmp=[[NSString alloc] initWithBytes:buffer length:len encoding:NSUTF8StringEncoding];
                        if(tmp.length>0) {
                           [total appendString:tmp];
 //                            if ([array[0]  isEqual: @"   {\"MessageID\""]) {
 //                                total = [[NSMutableString alloc]   init];
  //                                [total appendString: tmp];
  //                            } else {
  //                                [total appendString: tmp];
  //                            }
                       }
                     }//if
                      //else
                 //    break;
                 }//while
                  if(lenAll>0)
                  {
                     [self messageReceived:total];
                   }//if
   //                  NSArray *array = [total componentsSeparatedByString:@":"];
  //                   if (([array[array.count - 1] rangeOfString:@"}]}"].location != NSNotFound) || ([array[array.count - 1] rangeOfString:@"}}"].location != NSNotFound)) {
  //                    total = [[NSMutableString alloc] init];
 //                   }
           }//if
           break;
       case NSStreamEventEndEncountered:
           //[self closeSocket:theStream];
           break;
       case NSStreamEventErrorOccurred:
           [self closeSocket:theStream];
           break;
       case NSStreamEventOpenCompleted:
           socketOpened=1;
           [self performSelector:@selector(sendCustomerId) withObject:nil afterDelay:1];
           break;
       default:
       {
           //[self closeSocket:theStream];
       }//default
    }//switch
 }//Event

  -(void)tryOpenning
  {
      [self canceltryOpenning];
      [self performSelector:@selector(openSocket) withObject:nil afterDelay:30];
  }//tryOpenning

  -(void)canceltryOpenning
  {
      [NSObject cancelPreviousPerformRequestsWithTarget:self selector:@selector(openSocket) object:nil];
  }//canceltryOpenning

  - (int)sendData :(NSString *)message
  {
      if(socketOpened==0)
          return -1;

      NSString *response   = [NSString stringWithFormat:@"%@\r\n",message];
      NSData *data = [[NSData alloc] initWithData:[response dataUsingEncoding:NSUTF8StringEncoding]];
       [outputStream write:[data bytes] maxLength:[data length]];

       return 1;
   }//sendData
   - (void) messageReceived:(NSString *)message
   {   
       DataLayer *data=[[DataLayer alloc]init];
       [data analyzeMessage:message];
    }//messageReceived

    -(void)closeSocket:(NSStream *)theStream
    {
        if(socketOpened==1)
        {
           [theStream close];
           [theStream removeFromRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode];
           theStream = nil;
           socketOpened=0;
       }//if
       [self tryOpenning];
     }//closeSocket

   -(void)closeSocket2
   {
       if(socketOpened==1)
       {
           [streamForClose close];
           [streamForClose removeFromRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode];
           streamForClose = nil;
           socketOpened=0;
        }//if
   }//closeSocket2

   -(void)sendCustomerId
   {
       DataLayer *dLayer=[[DataLayer alloc]init];
       Setting *setObj=[dLayer getSetting];

       NSDictionary *dic=[NSDictionary dictionaryWithObjectsAndKeys:[NSString stringWithFormat:@"%d",[setObj.customerId intValue]],@"CustomerId",[NSString stringWithFormat:@"%d",[setObj.personId intValue]],@"PersonID",setObj.exKey,@"ExKey", nil];
       NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dic options:0 error:nil];
       NSString *JSONString = [[NSString alloc] initWithBytes:[jsonData bytes] length:[jsonData length] encoding:NSUTF8StringEncoding];
   [self sendData:JSONString];

   }//sendCustomerId

   -(void)Sync
   {
       DataLayer *dLayer=[[DataLayer alloc]init];
       Person *perObj=[dLayer getCurrentPerson];

       NSLog(@"lastMessageId=%d" , perObj.lastMessageId.intValue);

       NSDictionary *dic=[[NSDictionary alloc]initWithObjectsAndKeys:perObj.lastMessageId,@"LastMessageID",@"1.0",@"AppVerCode", nil];
       NSDictionary *dic2=[[NSDictionary alloc] initWithObjectsAndKeys:dic,@"SyncData",@"0",@"MessageID",perObj.personId,@"PersonID",@"2",@"Type",@"2",@"Action",@"2016-12-03 12:00:00",@"Date", nil];

       NSString *st=[dLayer makeJson:dic2];
       [self sendData : st];
    }//Sync





   @end

1 个答案:

答案 0 :(得分:0)

// SocketClient.h

#import <Foundation/Foundation.h>

typedef void (^OnIncoming)(NSString *message, NSOutputStream *outputStream);
typedef void (^OnReady)(NSOutputStream *outputStream);

@interface SocketClient : NSObject <NSStreamDelegate>

- (void)connect:(NSString*)host port:(int)port onReady:(OnReady)onReady onIncoming:(OnIncoming)onIncoming;
- (void)writeOut:(NSString *)s;

@end

// SocketClient.m

#import "SocketClient.h"

@interface SocketClient() {
    NSInputStream *inputStream;
    NSOutputStream *outputStream;
    bool ready;
}

@property OnReady onReady;
@property OnIncoming onIncoming;

@end

@implementation SocketClient

- (void)connect:(NSString*)host port:(int)port onReady:(OnReady)onReady onIncoming:(OnIncoming)onIncoming {
    ready = false;
    self.onReady = onReady;
    self.onIncoming = onIncoming;

    CFReadStreamRef readStream;
    CFWriteStreamRef writeStream;
    CFStreamCreatePairWithSocketToHost(kCFAllocatorDefault, (__bridge CFStringRef)(host), port, &readStream, &writeStream);

    if(!CFWriteStreamOpen(writeStream)) {
        NSLog(@"Error, writeStream not open");
        return;
    }

    inputStream = (__bridge NSInputStream *)readStream;
    outputStream = (__bridge NSOutputStream *)writeStream;

    [inputStream setDelegate:self];
    [outputStream setDelegate:self];

    [inputStream scheduleInRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode];
    [outputStream scheduleInRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode];

    [inputStream open];
    [outputStream open];

}

- (void)stream:(NSStream *)stream handleEvent:(NSStreamEvent)event {
    NSLog(@"Stream triggered.");

    switch(event) {
        case NSStreamEventHasSpaceAvailable: {
            if(stream == outputStream) {
                NSLog(@"outputStream is ready.");
                if (!ready) {
                    self.onReady(outputStream);
                    ready = true;
                }
            }
            break;
        }
        case NSStreamEventHasBytesAvailable: {
            if(stream == inputStream) {
                NSLog(@"inputStream is ready.");

                uint8_t buf[1024];
                NSInteger len = 0;

                len = [inputStream read:buf maxLength:1024];

                if(len > 0) {
                    NSMutableData* data=[[NSMutableData alloc] initWithLength:0];
                    [data appendBytes: (const void *)buf length:len];
                    NSString *s = [[NSString alloc] initWithData:data encoding:NSASCIIStringEncoding];

                    self.onIncoming(s, outputStream);
                }
            }
            break;
        }
        default: {
            NSLog(@"Stream is sending an Event: %lu", (unsigned long)event);
            break;
        }
    }
}

- (void)writeOut:(NSString *)s {
    uint8_t *buf = (uint8_t *)[[NSString stringWithFormat:@"%@\n", s] UTF8String];
    [outputStream write:buf maxLength:strlen((char *)buf)];
    NSLog(@"Writing out: %@", s);
}

@end