所以我在
Swift中使用套接字并试图将应用程序与我的服务器连接起来.我让应用程序连接到服务器的IP地址,并在服务器上使用netcat进行测试.在执行期间,应用程序的控制台输出显示它已成功连接到服务器.但是,流委托似乎没有响应.当我输入netcat时,app控制台没有打印任何内容.我已经搜索了很长一段时间,发现我的实现与其他实现非常相似.也许我在这里遗漏了一些我看不到的东西.
任何想到这个问题的人都将不胜感激!
代码如下:
import UIKit class ViewController: UIViewController,StreamDelegate { let addr:String = "52.34.56.78" let port:Int = 1234 var inputStream: InputStream? var outputStream: OutputStream? override func viewDidLoad() { super.viewDidLoad() self.connect(host: addr,port: port) } func connect(host: String,port: Int) { Stream.getStreamsToHost(withName: host,port: port,inputStream: &inputStream,outputStream: &outputStream) if inputStream != nil && outputStream != nil { inputStream!.delegate = self outputStream!.delegate = self inputStream!.schedule(in: RunLoop.main,forMode: RunLoopMode.defaultRunLoopMode) outputStream!.schedule(in: RunLoop.main,forMode: RunLoopMode.defaultRunLoopMode) inputStream!.open() outputStream!.open() print("successfully connected") } else { print("connection unsuccessful") } } func stream(aStream: Stream,handleEvent eventCode: Stream.Event) { if aStream === inputStream { switch eventCode { case Stream.Event.errorOccurred: print("input: ErrorOccurred: \(aStream.streamError?.localizedDescription)") break case Stream.Event.openCompleted: print("input: OpenCompleted") break case Stream.Event.hasBytesAvailable: print("input: HasBytesAvailable") break default: break } } else { print("unknown stuff happened") } } }