1
我正在使用CFStream構建IOS套接字客戶端。我設法連接到我的測試服務器並從中接收消息。問題是如果客戶端發送消息服務器無法接收它,並且之後客戶端不會收到來自服務器的任何消息。我的代碼如下。什麼可能是錯的?無法通過IOS套接字發送消息
- (void)initCommunicationWithAddress:(NSString*) address withPort:(int) port
{
CFReadStreamRef readStream;
CFWriteStreamRef writeStream;
CFStreamCreatePairWithSocketToHost(NULL, (__bridge CFStringRef)address, port, &readStream, &writeStream);
self.inputStream = (__bridge_transfer NSInputStream *)readStream;
self.outputStream = (__bridge_transfer NSOutputStream *)writeStream;
[self.inputStream setDelegate:self];
[self.outputStream setDelegate:self];
[self.inputStream scheduleInRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode];
[self.outputStream scheduleInRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode];
[self.inputStream open];
[self.outputStream open];
NSLog(@"Socket Init: %@", @"");
}
- (void)sendMessage:(NSString*)msg
{
msg = @"hello";
NSLog(@"SendMessage: %@", msg);
NSData *data = [[NSData alloc] initWithData:[msg dataUsingEncoding:NSASCIIStringEncoding]];
[self.outputStream write:[data bytes] maxLength:[data length]];
}
- (void)stream:(NSStream *)theStream handleEvent:(NSStreamEvent)streamEvent {
switch (streamEvent) {
case NSStreamEventOpenCompleted:
[self streamOpened];
break;
case NSStreamEventHasBytesAvailable:
NSLog(@"Stream Bytes Available:%@", @"");
if (theStream == self.inputStream) {
NSMutableData* data = [NSMutableData data];
uint8_t buffer[1024];
int len;
int bytesRead = 0;
while ([self.inputStream hasBytesAvailable])
{
len = [self.inputStream read:buffer maxLength:sizeof(buffer)];
if (len > 0) {
[data appendBytes:(const void *)buffer length:len];
bytesRead = bytesRead + len;
}
}
NSString* output = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
if (nil != output) {
[self HandleServerMessage: output];
}
}
break;
case NSStreamEventErrorOccurred:
NSLog(@"Stream Error:%@", @"");
[self streamError];
break;
case NSStreamEventEndEncountered:
NSLog(@"Stream Event End:%@", @"");
[theStream close];
[theStream removeFromRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode];
[self streamEnd];
break;
default:
NSLog(@"Unknown event");
}
}
你不會在'NSStreamEventErrorOccurred'或'NSStreamEventEndEncountered:'中得到任何錯誤嗎?爲什麼你需要'[self streamEnd];'? –
在旁邊注意看一看可能已經爲你完成工作的SocketRocket。 https://github.com/square/SocketRocket –
你可能想要使用一個現有的庫/框架,如CocoaAsyncSocket https://github.com/robbiehanson/CocoaAsyncSocket這是更容易使用 – howanghk