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") } } }
source share