2016-07-23 70 views
-1

保持冷靜,很可能這個問題不是重複的。 我已經嘗試了所有的堆棧溢出解決方案,但沒有爲我工作。 我有一個客戶端線程發送和接收來自另一主機的「keepalive」字符串(ping)。如果它沒有收到KeepAliveMax中的「Keepalive」,它會關閉這些流並說再見(理論上,但這還沒有起作用)。 現在我的問題是,我用一個NSTimer調用updateKeepAlive函數,但它永遠不會被調用..我不明白爲什麼:( 我也嘗試過手動設置NSTimer RunLoop,但它不起作用NSTimer永遠不會調用選擇器功能(Swift)

後續是代碼的一部分,其中選擇器功能應該被初始化,並呼籲每一秒:

public class Client: NSObject, NSStreamDelegate { 

var serverAddress: CFString 
let serverPort: UInt32 = 50000 

private var inputStream: NSInputStream! 
private var outputStream: NSOutputStream! 
private var connecting:Bool 
private var byteRead:Int 
private var byteWrite:Int 
private let keepAliveMax:Double = 5000 
private var keepAliveTime:Double 
private var connected:Bool 
var timer: NSTimer? 

init(ip:String) { 
    serverAddress = ip 
    connecting = false 
    connected = false 
    byteRead = 0 
    byteWrite = 0 
    keepAliveTime = 0 

    super.init() 

    let thread = NSThread(target:self, selector:#selector(connect), object:nil) 

    thread.start() 

    print("thread is started and now I can continue with other tasks..") 

} 

func connect() { 

    connecting = true 

    while connecting { 
     print("connecting...") 

     var readStream: Unmanaged<CFReadStream>? 
     var writeStream: Unmanaged<CFWriteStream>? 

     CFStreamCreatePairWithSocketToHost(nil, self.serverAddress, self.serverPort, &readStream, &writeStream) 

     // Documentation suggests readStream and writeStream can be assumed to 
     // be non-nil. If you believe otherwise, you can test if either is nil 
     // and implement whatever error-handling you wish. 

     self.inputStream = readStream!.takeRetainedValue() 
     self.outputStream = writeStream!.takeRetainedValue() 

     self.inputStream.delegate = self 
     self.outputStream.delegate = self 

     self.inputStream.scheduleInRunLoop(NSRunLoop.currentRunLoop(), forMode: NSDefaultRunLoopMode) 
     self.outputStream.scheduleInRunLoop(NSRunLoop.currentRunLoop(), forMode: NSDefaultRunLoopMode) 

     self.inputStream.open() 
     self.outputStream.open() 

     // send handshake 

     byteWrite = writeLine("handshake") 
     print("written: \(byteWrite) for handshake") 


     // wait to receive handshake 
     print("waintig for handshake...") 


     if readLine() == "handshake" { 
      connected = true 

      print("Client: connection estabilished correctly") 

      // close the waiting popup and start with SendBox... 
      // in progress... 

      // send keepAlive 
      byteWrite = writeLine("keepalive") 
      print("written: \(byteWrite) for keepalive") 


      //======================== THIS NOT WORK PROPERLY ============================================================ 

      timer = NSTimer.scheduledTimerWithTimeInterval(1, target: self, selector: #selector(Client.updateKeepAlive), userInfo: nil, repeats: true) 

      /* 
      timer = NSTimer(timeInterval: 1, target: self, selector: #selector(Client.updateKeepAlive), userInfo: nil, repeats: true) 

      NSRunLoop.currentRunLoop().addTimer(timer!, forMode: NSRunLoopCommonModes) 
      */ 

      //============================================================================================================ 

      keepAliveTime = NSDate().timeIntervalSince1970 * 1000 

      print("Client: Timer started") 

      while self.inputStream.streamStatus != NSStreamStatus.Closed || 
       self.outputStream.streamStatus != NSStreamStatus.Closed 
      { 
       print("Client: under the while of keepAlive"); 

       if readLine() == "keepalive" 
       { 
        keepAliveTime = NSDate().timeIntervalSince1970 * 1000 
        writeLine("keepalive") 

        print("Client: keepalive received"); 
       } 
       else 
       { 
        print("Client: not keepalive: "); 
        // close streams...... work in progress 
        break 

       } 

       sleep(1) 
      } 

     } 
     else{ 
      print("wrong handshake") 
     } 


     print("closing streams..") 
     connecting = false 

     self.inputStream.close() 
     self.outputStream.close() 
     self.timer?.invalidate() 
    } 

} 

而且遵循的是updateKeepAlive功能:

func updateKeepAlive(){ 

    print("in updateKeepalive function") // <---- NEVER PRINTED 

    /* in progress ..... 

    ........./* 
} 

回答

0

在一個新的線程開始時,有沒有inp ut源或定時器附加到運行循環。所以運行循環,而不是積極的。您可以在調用scheduledTimerWithTimeInterval之後調用run函數。

timer = NSTimer.scheduledTimerWithTimeInterval(1, target: self, selector: #selector(TimerTest.updateKeepAlive), userInfo: nil, repeats: true) 
NSRunLoop.currentRunLoop().run() 
相關問題