2016-07-22 56 views
5

我試圖建立我的Java應用程序和相對(進展)的iOS應用程序之間的通信。 插座被打開後,iOS的應用程序(客戶端)寫一個「握手」字符串轉換成流,然後等待讀取數據流(我認爲)。 當代的Java應用程序(服務器,iOS的應用程序之前啓動)成功打開插座和等待的BufferedReader讀爲「握手」,在這一點上這兩個應用程序將被阻止。 我不明白它是如何可能?TCP通信

按照iOS的代碼部分:

public class Client: NSObject, NSStreamDelegate { 

var serverAddress: CFString 
let serverPort: UInt32 = 50000 

private var inputStream: NSInputStream! 
private var outputStream: NSOutputStream! 
private var connecting:Bool 

init(ip:String) { 
    serverAddress = ip 
    connecting = false 

    super.init() 

    connect() 
} 

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 

     let handshake: NSData = "handshake".dataUsingEncoding(NSUTF8StringEncoding)! 
     let returnVal = self.outputStream.write(UnsafePointer<UInt8>(handshake.bytes), maxLength: handshake.length) 
     print("written: \(returnVal)") 


     // wait to receive handshake 

     let bufferSize = 1024 
     var buffer = Array<UInt8>(count: bufferSize, repeatedValue: 0) 

     print("waintig for handshake...") 

     let bytesRead = inputStream.read(&buffer, maxLength: bufferSize) 
     if bytesRead >= 0 { 
      var output = NSString(bytes: &buffer, length: bytesRead, encoding: NSUTF8StringEncoding) 
      print("received from host \(serverAddress): \(output)") 
     } else { 
      // Handle error 
     } 

     connecting = false 

     self.inputStream.close() 
     self.outputStream.close() 
    } 


} 

public func stream(stream: NSStream, handleEvent eventCode: NSStreamEvent) { 
    print("stream event") 

    if stream === inputStream { 
     switch eventCode { 
     case NSStreamEvent.ErrorOccurred: 
      print("input: ErrorOccurred: \(stream.streamError?.description)") 
     case NSStreamEvent.OpenCompleted: 
      print("input: OpenCompleted") 
     case NSStreamEvent.HasBytesAvailable: 
      print("input: HasBytesAvailable") 

      // Here you can `read()` from `inputStream` 

     default: 
      break 
     } 
    } 
    else if stream === outputStream { 
     switch eventCode { 
     case NSStreamEvent.ErrorOccurred: 
      print("output: ErrorOccurred: \(stream.streamError?.description)") 
     case NSStreamEvent.OpenCompleted: 
      print("output: OpenCompleted") 
     case NSStreamEvent.HasSpaceAvailable: 
      print("output: HasSpaceAvailable") 

      // Here you can write() to `outputStream` 
      break 

     default: 
      break 
     } 
    } 

} 

}

遵循Java代碼的部分(它的其他計算機之間的工作完全使用相同的Java應用程序):

public void run() 
{ 
    System.out.println("Server.java: waiting for connection"); 

    //accept 
    try 
    { 
     serverSocket = new ServerSocket(portNumber); 
     clientSocket = serverSocket.accept(); 
     reader = new BufferedReader(new InputStreamReader(clientSocket.getInputStream())); 
     writer = new BufferedWriter(new OutputStreamWriter(clientSocket.getOutputStream())); 

     System.out.println("Server.java: connected to " + clientSocket.getInetAddress()); 

     // check for input request type 
     String line = reader.readLine(); // <----BLOCKED HERE! 

     if(line.equals("handshake")) 
     { 
      connected = true; 

      // send acceptation 
      System.out.println("Server.java: Sending handshake, waiting response"); 
      writer.write("handshake"); 
      writer.newLine(); 
      writer.flush(); 

      // .... and the rest of code... 

當我關閉了iOS應用程序從讀Java應用程序解鎖,打印正確接收到的握手,然後繼續自己的工作。 有人可以幫我嗎?

回答

2

我覺得你的問題是,你永遠不會結束在斯威夫特程序就行了。

什麼的readLine確實根據BufferReader的文檔:

「讀取一行的文本行被認爲是由一個 換行中的任何一個(‘\ n’)被終止,回車(」。 \ r'),或回車後立即換行。「

這意味着它期望換行符或通信結束。由於你的Swift應用程序不會發送任何新行字符,也不會關閉流,客戶端只是在等待。

嘗試換行('\ n')或回車('\ r')並查看結果如何。

+0

哦,你是對的!現在它的作品,非常感謝! :) – sgira

+0

謝謝!非常有幫助的答案! –