andeey
andeey

Reputation: 63

Swift 3 inputstream and outputstream connecting but no stream

I have an issue with connecting to a Java socket with StreamDelegate in Swift 3. I am currently in the process of rewriting a big Objective C project where this piece of code runs like a charm, but I can't seem to be able to get it to work in Swift 3. The problem I am having is that the stream function never runs. So "Stream!" is never printed out. The Stream.Status after self.outputStream.open() is called is 1 (opening). The code runs without any problems and "Opening streams on thread:" gets called.

The socket I am trying to connect to is a Java socket.

Note: I have experienced that the debugger has printed out a message saying there is no handler attached, but I do not know it is related.

I have found a couple of similar posts, but not on this exact problem. If anyone has any ideas, I would be happy to hear them out! Thanks to anyone who tries to help.

import Foundation

@objc class SocketConnector : NSObject, StreamDelegate {
    var inputStream : InputStream!
    var outputStream : OutputStream!

    var lock : NSRecursiveLock

    override init () {
        lock = NSRecursiveLock.init()
    }

func connect (host : String, port : Int) -> Bool {
    lock.lock()
    var readStream : Unmanaged<CFReadStream>?
    var writeStream : Unmanaged<CFWriteStream>?

    CFStreamCreatePairWithSocketToHost(nil, host as CFString!, UInt32(port), &readStream, &writeStream)

    inputStream = readStream!.takeRetainedValue()
    outputStream = writeStream!.takeRetainedValue()

    self.inputStream.delegate = self
    self.outputStream.delegate = self

    self.inputStream.schedule(in: RunLoop.current, forMode: .defaultRunLoopMode)
    self.outputStream.schedule(in: RunLoop.current, forMode: .defaultRunLoopMode)

    self.inputStream.open()
    self.outputStream.open()

    print("Opening streams on thread: %@", Thread.current)

    lock.unlock()

    return true
}

func stream (aStream : Stream, handleEvent eventCode : Stream.Event) {
    print("Stream!")
    switch eventCode {
    case Stream.Event.hasBytesAvailable:
        print("Stream has bytes:");
        break;
    case Stream.Event.errorOccurred:
        print("Stream error occurred: %@",aStream.streamError?.localizedDescription)
    case Stream.Event.openCompleted:
        print("Stream has bytes:")
        break
    case Stream.Event.endEncountered:
        print("Stream ended")
        self.closeStreams()
        break
    default:
        break
    }
}

Upvotes: 3

Views: 2533

Answers (1)

Bao HQ
Bao HQ

Reputation: 1184

Your implement is not compatible with stream method of StreamDelegate. You must change to this:

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

instead of

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

Upvotes: 3

Related Questions