Reflective Streaming Delegate in Swift

So, I played with sockets in Swift and tried to connect the application to my server. I connected the application to the server IP address and used netcat on the server for testing. At run time, console output from the application showed that it was successfully connected to the server. However, the thread delegate does not seem responsive. When I typed netcat , the application console did not print anything. I searched for quite a while and found that my implementation is very similar to the others. Perhaps I am missing something here that I do not see.

Any thought on this issue would be greatly appreciated!

The code is attached below:

 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") } } } 
+5
source share
1 answer

So, after a lot of testing and errors, I finally realized that the stream () function does not work just because the signature of this function is incorrect / outdated.

Here is what I used:

func stream(aStream: Stream, handleEvent eventCode: Stream.Event)

But actually it should be:

func stream(_ aStream: Stream, handle eventCode: Stream.Event)

This is probably a syntax conversion from a previous version of Swift to Swift 3. The Xcode compiler usually detects legacy functions / syntax, but unfortunately did not catch it.

Hope my answer can help those still suffering from this problem.

+10
source

Source: https://habr.com/ru/post/1261231/


All Articles