基本上我遇到的问题是我的基于tcp / ip的服务器随机没有收到我发送的一些数据包。我确定它实际上不是随机的,但我还没弄清楚导致问题的原因。这个确切的代码在我的应用程序的早期版本中完美运行。这是我的代码:
初始化网络连接:
- (void)initNetworkCommunication {
CFReadStreamRef readStream;
CFWriteStreamRef writeStream;
int randomPort = [self randomPort];
CFStreamCreatePairWithSocketToHost(NULL,(__bridge CFStringRef)kSERVER_ADDRESS, randomPort, &readStream, &writeStream);
inputStream = (__bridge NSInputStream *)readStream;
outputStream = (__bridge NSOutputStream *)writeStream;
[inputStream setDelegate:self];
[outputStream setDelegate:self];
[outputStream scheduleInRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode];
[outputStream open];
}
函数randomPort
随机返回1244或1245,它们是服务器的端口号引用。常量kSERVER_ADDRESS
只是一个存储服务器地址的字符串。
要发送数据包我使用此功能:
- (void)sendPacket:(NSData *)packet {
[self initNetworkCommunication];
[outputStream write:[packet bytes] maxLength:[packet length]];
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
[self performSelector:@selector(scheduleInThread:) onThread:[[self class] networkThread] withObject:nil waitUntilDone:YES];
});
}
安排输入流:
- (void)scheduleInThread:(id)sender {
[inputStream scheduleInRunLoop:[NSRunLoop currentRunLoop] forMode:NSRunLoopCommonModes];
[inputStream open];
}
处理网络事件:
- (void)stream:(NSStream *)stream handleEvent:(NSStreamEvent)eventCode {
BOOL shouldClose = NO;
switch(eventCode) {
case NSStreamEventHasBytesAvailable:
{
NSLog(@"bytes available");
uint8_t *buffer = malloc(10000);
NSInteger len = [inputStream read:buffer maxLength:10000];
self.networkData = [[NSData alloc] initWithBytesNoCopy:buffer length:len];
NSString *dataString = [[NSString alloc] initWithData:self.networkData encoding:NSUTF8StringEncoding];
NSLog(@"%@", dataString);
NSLog(@"length: %li", len);
[self.delegate serverAgent:self didReceiveNetworkData:YES];
break;
}
case NSStreamEventNone:
{
break;
}
case NSStreamEventHasSpaceAvailable:
{
break;
}
case NSStreamEventEndEncountered:
{
shouldClose = YES;
[self closeThread];
break;
}
case NSStreamEventErrorOccurred:
{
isNetworkAvailable = NO;
shouldClose = YES;
[[NSNotificationCenter defaultCenter] postNotificationName:kNETWORK_UNAVAILABLE_NOTIFICATION object:nil];
break;
}
case NSStreamEventOpenCompleted: {
isNetworkAvailable = YES;
[[NSNotificationCenter defaultCenter] postNotificationName:kNETWORK_AVAILABLE_NOTIFICATION object:nil];
break;
}
}
if(shouldClose) {
[stream close];
}
}
我已经验证了大约70%的时间服务器没有收到数据包,大约30%的时间服务器收到数据包,一切都运行良好。我还验证了它不是端口号的问题,两个端口都正常工作。此外,没有发生网络错误。有时服务器在长时间延迟(15-20秒)后收到数据包,有时根本没有收到数据包。如果有人能够对这个问题有所了解,那将非常感激。在使用iOS的tcp / ip协议时,我绝对是一个新手。先感谢您。
答案 0 :(得分:0)
您确定数据包正在离开手机吗?您可以使用Charles(How to use Charles Proxy on the Xcode 6 (iOS 8) Simulator?)或Wireshark查找离开您应用的网络活动,以确保它们被发送到服务器。
如果数据包肯定会离开应用程序,那么服务器是否有问题?你可以尝试不同的服务器或在本地测试,以尝试查找错误是否与您的应用程序或服务器有关。