So I was playing around with sockets in Swift and trying to connect the app with my server. I was having the app connect to the IP address of the server and used netcat
on the server for testing. During execution, the console output from the app showed it had successfully connected to the server. However, the stream delegate does not seem to be responsive. When I typed into netcat
, the app console did not print anything. I have searched for quite a while and found that my implementation is pretty similar to others. Perhaps I am missing something here that I do not see.
Any thought to this problem would be greatly appreciated!
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")
}
}
}
inputStream.hasBytesAvailable
, it returned true after I sent something vianetcat
. I suspect this has something to do with not properly configuring the stream delegate, or maybe the run loop. – Malraux