我在使用Swift 3中的StreamDelegate连接到Java套接字时遇到了问题。我目前正在重写一个大的Objective C项目,其中这段代码像魅力一样运行,但我似乎无法做到能够让它在Swift 3中工作。我遇到的问题是流函数永远不会运行。所以“流!”永远不会打印出来。调用Stream.Status
之后的self.outputStream.open()
为1(开放)。代码运行没有任何问题,并且“在线程上打开流:”被调用。
我尝试连接的套接字是一个Java套接字。
注意:我经历过调试器打印出一条消息,说没有附加处理程序,但我不知道它是相关的。
我找到了几个类似的帖子,但没有找到这个确切的问题。如果有人有任何想法,我会很高兴听到他们!感谢任何试图提供帮助的人。
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
}
}
答案 0 :(得分:2)
您的工具与StreamDelegate的stream方法不兼容。 你必须改为:
func stream(_ aStream:Stream,handle eventCode:Stream.Event)
而不是
func stream(aStream:Stream,handleEvent eventCode:Stream.Event