实现自动逻辑回复功能
- 在 监听接入客户端的方法中 监听到接入后 写入客户端数据
- (void)socket:(GCDAsyncSocket *)sock didAcceptNewSocket:(GCDAsyncSocket *)newSocket {
NSLog(@"服务端 %@", sock);
NSLog(@"客户端 %@", newSocket);
[self.clientSockets addObject:newSocket];
NSMutableString *mutableStr = [NSMutableString string];
[mutableStr appendString:@"欢迎来到10086在线服务,请输入下面的数字选择服务\n"];
[mutableStr appendString:@"[0]在线充值\n"];
[mutableStr appendString:@"[1]在线投诉\n"];
[mutableStr appendString:@"[2]优惠信息\n"];
[mutableStr appendString:@"[3]special services\n"];
[newSocket writeData:[mutableStr dataUsingEncoding:NSUTF8StringEncoding] withTimeout:-1 tag:0];
// 监听客户端是否写入数据
// timeOut: -1 暂时不需要 超时时间 tag暂时不需要 传0
[newSocket readDataWithTimeout:-1 tag:0];
}
- (void)socket:(GCDAsyncSocket *)sock didReadData:(NSData *)data withTag:(long)tag {
NSLog(@"客户端 %@", sock);
NSString *dataStr = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
NSLog(@"data --- %@", dataStr);
NSInteger index = [dataStr integerValue];
NSString *responseStr = nil;
switch (index) {
case 0:
responseStr = @"充值服务暂停中...\n";
break;
case 1:
responseStr = @"投诉服务暂停中...\n";
break;
case 2:
responseStr = @"优惠信息没有...\n";
break;
case 3:
responseStr = @"SB 怎么可能有特殊服务...\n";
break;
case 4:
responseStr = @"退出成功...\n";
break;
default:
responseStr = @"指令无效...\n";
break;
}
#####退出连接的话 将客户端socket 从数组中移除即可
if (index == 4) {
[self.clientSockets removeObject:sock];
}
// 服务端接收到客户端发送的数据之后 返回数据给 客户端
// 我们将接受到的数据返回回去
[sock writeData:[responseStr dataUsingEncoding:NSUTF8StringEncoding] withTimeout:-1 tag:0];
[sock readDataWithTimeout:-1 tag:0];
}