套接字连接期间IOS UI冻结

时间:2017-12-22 22:26:27

标签: ios sockets stream

我不太了解流或套接字连接,但似乎没有别的东西可以做我需要的。我正在尝试组合一个简单的连接,这将允许我监视一个打开的连接并在我收到它时读取该输入。

连接正常,但UI在连接设置期间冻结。我不确定如何将其推送到后台,因此它不会干扰UI。

套接字类

import Foundation

protocol SocketDelegate {
  func hasBytes(stream: Stream)
  func opened(stream: Stream)
  func error(stream: Stream)
  func closed(stream: Stream)
  func other(stream: Stream)
}

class Socket: NSObject, StreamDelegate {

  fileprivate var hostname: String
  fileprivate var port: Int

  fileprivate var delegate: SocketDelegate?

  fileprivate var istreamopen: Bool
  fileprivate var ostreamopen: Bool

  fileprivate var istream : InputStream?
  fileprivate var ostream : OutputStream?

  init(hostname: String, port: Int) {

    self.hostname = hostname
    self.port = port
    self.istreamopen = false
    self.ostreamopen = false

    Stream.getStreamsToHost(withName: self.hostname, port: self.port, inputStream: &self.istream, outputStream: &self.ostream)


    self.istream!.schedule(in: RunLoop.current, forMode: RunLoopMode.defaultRunLoopMode)
    self.ostream!.schedule(in: RunLoop.current, forMode: RunLoopMode.defaultRunLoopMode)

  }


  func getInputStream() -> InputStream {
    return istream!
  }

  func getOutputStream() -> OutputStream {
    return ostream!
  }

  func Connect() -> Void {

    self.istream?.delegate = self
    self.ostream?.delegate = self

    istream!.open()
    ostream!.open()
  }

  func DisConnect() -> Void {
    istream!.close()
    ostream!.close()
    istreamopen = false
    ostreamopen = false
  }

  func write(bytes: [UInt8]) {
    ostream?.write(bytes, maxLength: (bytes).count)
  }

  func write(string: String) {
    ostream?.write([UInt8](string.utf8), maxLength: ([UInt8](string.utf8)).count)
  }

  func read(bufferSize: Int) -> String {
    var output = String()
    var buffer = [UInt8](repeating: 0, count: bufferSize)
    //while (self.istream?.hasBytesAvailable)! {
      //print("HELLO")
      let bytesRead: Int = self.istream!.read(&buffer, maxLength: buffer.count)
      if bytesRead >= 0 {
        output += NSString(bytes: UnsafePointer(buffer), length: bytesRead, encoding: String.Encoding.ascii.rawValue)! as String
      } else {
        output = "# Stream read() error"
      }
      //print(output)
    //}
    return output
  }


  func setDelegate(delegate: SocketDelegate) -> Void {
    self.delegate = delegate
  }

  func stream(_ aStream: Stream, handle eventCode: Stream.Event) {
    //print("\(aStream) Stream!")
    switch eventCode {
    case Stream.Event.hasBytesAvailable:
      delegate?.hasBytes(stream: aStream)
      break;
    case Stream.Event.errorOccurred:
      //print("Stream error occurred: %@",aStream.streamError?.localizedDescription ?? "ERROR")
      delegate?.error(stream: aStream)
    case Stream.Event.openCompleted:
      //print("\(aStream)  --  \(self.istream)  --  \(self.ostream)")
      if (aStream == self.istream) {
        self.istreamopen = true
        //print("\(self.istream) Open")
      } else if (aStream === self.ostream) {
        self.ostreamopen = true
        //print("\(self.ostream) Open")
      }
      delegate?.opened(stream: aStream)
      break
    case Stream.Event.endEncountered:
      //print("Stream ended")
      if (aStream === self.istream) {
        self.istreamopen = false
      } else if (aStream === self.ostream) {
        self.ostreamopen = false
      }
      delegate?.closed(stream: aStream)
      break
    default:
      delegate?.other(stream: aStream)
      break
    }
  }

  func isConnected() -> Bool {
    return (istreamopen && ostreamopen)
  }


}

2 个答案:

答案 0 :(得分:1)

我认为这不是失败的连接。这是SSL协商期间的初始写入。我在DispatchQueue中包装了写命令,它似乎解决了这个问题。

  func write(bytes: [UInt8]) {
    DispatchQueue.global(qos: .background).async {
      self.ostream?.write(bytes, maxLength: (bytes).count)
    }
  }

  func write(string: String) {
    DispatchQueue.global(qos: .background).async {
      self.ostream?.write([UInt8](string.utf8), maxLength: ([UInt8](string.utf8)).count)
    }
  }

答案 1 :(得分:0)

我也尝试了它,它有很多问题,比如你现在面临的问题,所以尝试使用这个库,它会为你做很重的事情

socket.io-client-swift