我们目前正在开发一个 TLS-server-client-application。为了测试客户端发送一个内容为“0001”的命令,服务器发送一个答案。
客户端通过 NSOutputStream 的 write-method 发送数据。当数据第一次发送时,它完全到达。当我第二次或第三次发送它时,数据在第一个字节之后被拆分。服务器获得第一个“0”,然后是其余的“001”。我不知道为什么它是分裂的。
通信如下所示:
ServerConnect
发送到服务器:0001
从服务器接收:OK
发送到服务器:0
从服务器接收:错误
发送到服务器:001
从服务器接收:错误
发送到服务器:0
从服务器接收:错误
发送到服务器: 001
从服务器接收:错误
ServerDisconnect
我希望有人可以帮助我。
- (void)initNetworkCommunication:(NSString*)ns_IP :(UInt32)ui_Port :(BOOL)b_ValidateCertificate
{
CFReadStreamRef readStream;
CFWriteStreamRef writeStream;
CFStreamCreatePairWithSocketToHost(NULL, (__bridge CFStringRef)ns_IP, ui_Port, &readStream, &writeStream);
inputStream = (__bridge NSInputStream *)readStream;
outputStream = (__bridge NSOutputStream *)writeStream;
[inputStream setDelegate:(id)self];
[outputStream setDelegate:(id)self];
[inputStream scheduleInRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode];
[outputStream scheduleInRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode];
NSDictionary *settings = [[NSDictionary alloc] initWithObjectsAndKeys:
[NSNumber numberWithBool:b_ValidateCertificate], kCFStreamSSLValidatesCertificateChain,
[NSNumber numberWithBool:YES], kCFStreamPropertyShouldCloseNativeSocket,
kCFNull,kCFStreamSSLPeerName,
kCFStreamSocketSecurityLevelSSLv3, kCFStreamSSLLevel,
nil];
CFReadStreamSetProperty((CFReadStreamRef)inputStream, kCFStreamPropertySSLSettings, (CFTypeRef)settings);
CFWriteStreamSetProperty((CFWriteStreamRef)outputStream, kCFStreamPropertySSLSettings, (CFTypeRef)settings);
[inputStream open];
[outputStream open];
}
- (BOOL) sendData:(NSString*)ns_SendData :(NSUInteger)nui_bufferLength
{
NSUInteger nui_length = [ns_SendData length];
NSUInteger nui_chunkSize = nui_bufferLength;
NSUInteger nui_offset = 0;
long l_Result;
NSString *ns_response = [NSString stringWithFormat:@"%@", ns_SendData];
NSData *nd_data = [[NSData alloc] initWithData:[ns_response dataUsingEncoding:NSASCIIStringEncoding]];
// a none-ASCII-symbol exists
if ([nd_data length] == 0)
return FALSE;
// split the data
do {
NSUInteger nui_thisChunkSize = nui_length - nui_offset > nui_chunkSize ? nui_chunkSize : nui_length - nui_offset;
NSData* chunk = [NSData dataWithBytesNoCopy:(char *)[nd_data bytes] + nui_offset
length:nui_thisChunkSize
freeWhenDone:NO];
nui_offset += nui_thisChunkSize;
// send data to server
l_Result = [outputStream write:[chunk bytes] maxLength:[chunk length]];
NSLog(@"%s - %lu", __PRETTY_FUNCTION__, l_Result);
if (l_Result == -1) {
NSLog(@"error sending data");
return false;
}
} while (nui_offset < nui_length);
return true;
}