29,031
社区成员
发帖
与我相关
我的任务
分享
-(void)socket:(GCDAsyncSocket *)sock didReadData:(NSData *)data withTag:(long)tag
#import "CommandClient.h"
#import <UIKit/UIKit.h>
@implementation CommandClient
+ (CommandClient *)sharedInstance {
static CommandClient *sharedInstance = nil;
static dispatch_once_t once;
dispatch_once(&once, ^{
sharedInstance = [[self alloc] init];
});
return sharedInstance;
}
- (void)initialize {
static dispatch_once_t once;
dispatch_once(&once, ^{
NSLog(@"Start Creating GCDAsyncSocket");
FMUtils = objc_getClass("FMUtils");
socketClient =[[GCDAsyncSocket alloc] initWithDelegate:self delegateQueue:dispatch_get_main_queue()];
});
}
- (BOOL)startServer {
NSLog(@"Start startServer GCDAsyncSocket");
NSError *error;
NSString *host = @"192.168.0.9";
uint16_t port = 8666;
BOOL ret = [socketClient connectToHost:host onPort:port error:&error];
if (!ret) {
NSLog(@"socketClient Connection: %@", error);
}
return ret;
}
- (void)stopServer {
NSLog(@"Start stopServer GCDAsyncSocket");
[socketClient disconnect];
}
#pragma mark - GCDAsyncSocketDelegate
// 已连接
- (void)socket:(GCDAsyncSocket *)sock didConnectToHost:(NSString *)host port:(UInt16)port{
[socketClient readDataWithTimeout:-1 tag:0];
NSLog(@"Connected: %@:%d", host, port);
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"State" message:@"Connection Server Success!" delegate:self cancelButtonTitle:nil otherButtonTitles:nil];
[alert addButtonWithTitle:@"Yes"];
[alert show];
}
-(void)socket:(GCDAsyncSocket *)sock didReadData:(NSData *)data withTag:(long)tag{
NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableLeaves error:nil];
NSString* sName = [dict objectForKey:@"sName"];
if ([sName isEqual:@"getSkey"]) {
NSString* sid = [dict objectForKey:@"sid"];
NSString* result = [FMUtils encrySkey:sid];
NSData *requestData = [result dataUsingEncoding:NSUTF8StringEncoding];
[sock writeData:requestData withTimeout:-1. tag:0];
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"State" message:@"send Server Success!" delegate:self cancelButtonTitle:nil otherButtonTitles:nil]; //这两句注释掉就会百分百崩溃
[alert release]; //这两句注释掉就会百分百崩溃
}
[socketClient readDataWithTimeout:-1 tag:0];
}
- (void)socket:(GCDAsyncSocket *)sock didWriteDataWithTag:(long)tag
{
}
@end
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"State" message:@"send Server Success!" delegate:self cancelButtonTitle:nil otherButtonTitles:nil];
[alert release];