我想让TCP客户端在永久循环中发送和接收数据。我尝试过以下代码,但数据发送和接收只执行一次。
理想:
iOS ------> server
iOS <------ server
iOS ------> server
iOS <------ server
and forever ...
问题:
iOS ------> server
iOS <------ server
one time only
我的服务器代码没有问题,因为我已经在客户端本机c代码中测试了它。所以,我想知道我的Swift代码是否有问题。
var sendFlag:Bool = true;
func initTcpNetwork(host:String,port :Int,delegate:NSStreamDelegate? ) {
NSStream.getStreamsToHostWithName(host, port: port, inputStream: &inputstream, outputStream: &outputstream)
inputstream?.delegate=self;
outputstream?.delegate=self;
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_BACKGROUND, 0)){
self.printQueueLabel();
let loop = NSRunLoop.currentRunLoop();
self.inputstream?.scheduleInRunLoop(loop, forMode: NSDefaultRunLoopMode);
self.outputstream?.scheduleInRunLoop(loop, forMode: NSDefaultRunLoopMode);
self.inputstream?.open()
self.outputstream?.open()
loop.run();
}
}
func stream(aStream: NSStream, handleEvent eventCode: NSStreamEvent) {
switch (eventCode){
case NSStreamEvent.OpenCompleted:
NSLog("Stream opened");
break
case NSStreamEvent.HasSpaceAvailable:
NSLog("has space");
if(sendFlag) {
sendFlag = false;
var outputstream = aStream as? NSOutputStream;
var str = "0";
var data: NSData = str.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false)!;
outputstream?.write(UnsafePointer<UInt8>(data.bytes), maxLength: data.length);
}
break
case NSStreamEvent.HasBytesAvailable:
var inputstream = aStream as? NSInputStream;
var buffer = [UInt8](count: 4096, repeatedValue: 0);
while ((inputstream?.hasBytesAvailable) != nil) {
var len = inputstream?.read(&buffer, maxLength: 4096);
if (len > 0) {
var output: NSString = NSString(bytes:&buffer, length:len!, encoding:NSASCIIStringEncoding)!;
dispatch_async(dispatch_get_main_queue(), {
self.handleDataReceived(output);
})
}
}
self.sendFlag = true;
break
case NSStreamEvent.ErrorOccurred:
var err = aStream.streamError;
print(err?.description);
break
case NSStreamEvent.EndEncountered:
aStream.close();
aStream.removeFromRunLoop(NSRunLoop.currentRunLoop(), forMode: NSDefaultRunLoopMode);
break
default:
NSLog("unknown.")
}
}