我已经在我的项目中实现了套接字连接,并且工作正常。 但我的问题是我想在socket完成时发送一个字符串请求。
代表工作正常。
- (void)initNetworkCommunication
{
lastString=@"";
isSocketAuthorized=NO;
NSLog(@"$$$$$$$$$$$$$$$$$$$$$$$$$============socket connection INITIALISED....");
CFReadStreamRef readStream;
CFWriteStreamRef writeStream;
CFStreamCreatePairWithSocketToHost(NULL,(CFStringRef)@"XXX.XX.XXX.XX",XXXX, &readStream, &writeStream);
inputStream = (__bridge NSInputStream *)readStream;
outputStream = (__bridge NSOutputStream *)writeStream;
[inputStream setDelegate:self];
[outputStream setDelegate:self];
[inputStream scheduleInRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode];
[outputStream scheduleInRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode];
[inputStream open];
[outputStream open];
}
- (void)stream:(NSStream *)aStream handleEvent:(NSStreamEvent)eventCode
{
switch (eventCode) {
case NSStreamEventOpenCompleted:{
NSLog(@"Stream opened");
[self performSelectorInBackground:@selector(sendAuthRequest) withObject:nil];
}
break;
case NSStreamEventHasBytesAvailable:
{
if (aStream == inputStream) {
uint8_t buffer[1024];
int len;
while ([inputStream hasBytesAvailable]) {
len = [inputStream read:buffer maxLength:sizeof(buffer)];
if (len > 0) {
NSString *output = [[NSString alloc] initWithBytes:buffer length:len encoding:NSASCIIStringEncoding];
if (nil != output) {
// NSLog(@"server said: %@", output);
[self messageReceived:output];
}
}
}
}
}
break;
case NSStreamEventErrorOccurred:
NSLog(@"Can not connect to the host!");
break;
case NSStreamEventEndEncountered:
{
[aStream close];
[aStream removeFromRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode];
}
break;
default:
NSLog(@"Unknown event");
}
}
但是打开了两次流。为什么?谁能帮我。 感谢。
答案 0 :(得分:5)
经过很长一段时间的思考后,我开始知道我实际上是打开了两次开放流。第一次是输入流,第二次是输出流。最后我得到了解决方法,在一个名为no的事件中触发我的方法,我使用了NSStream类的条件。
case NSStreamEventOpenCompleted:{
if ([aStream isKindOfClass:[inputStream class]]) {
NSLog(@"Input stream opened");
}else{
NSLog(@"output stream opened");
[self performSelectorInBackground:@selector(sendAuthRequest) withObject:nil];
}
}