所以我的問題是讓一個InputStream在iOS平臺的swift中工作。我寫了一些代碼,並會在下面發佈,但基本上我有一個Android客戶端,它將數據發送到iOS客戶端的IP。不幸的是,Android客戶端說連接被拒絕連接到iOS客戶端。我真的不太確定我在這裏做錯了什麼,因爲我認爲代碼看起來很紮實,所以我有點困惑。順便說一句,這是我第一次使用swift(iOS)中的套接字,所以請理解我是新手,並且在這裏通過示例代碼來學習。在Swift 3(iOS)中創建一個通過套接字接收數據的InputStream
ViewControler.swift
var inputstream: InputStream?
var outputstream: OutputStream?
var host: CFString?
var port: UInt32?
override func viewDidLoad() {
super.viewDidLoad()
initNetworkCommunication()
}
func initNetworkCommunication(){
host = "192.168.1.187" as CFString
port = 55555
var readstream : Unmanaged<CFReadStream>?
var writestream : Unmanaged<CFWriteStream>?
CFStreamCreatePairWithSocketToHost(kCFAllocatorDefault, host!, port!, &readstream, &writestream)
inputstream? = readstream!.takeRetainedValue()
outputstream? = writestream!.takeRetainedValue()
inputstream?.delegate = self as! StreamDelegate
outputstream?.delegate = self as! StreamDelegate
inputstream?.schedule(in: RunLoop.current, forMode: RunLoopMode.defaultRunLoopMode)
outputstream?.schedule(in: RunLoop.current, forMode: RunLoopMode.defaultRunLoopMode)
inputstream?.open()
Status.text = "Input Stream Opened"
outputstream?.open()
Status.text = "Output Stream Opened"
}
func stream(_ aStream: Stream, handleEvent eventCode: Stream.Event) {
switch (eventCode){
case Stream.Event.errorOccurred:
print("Can not connect to the host!")
Status.text = "Cannot connect to: \(host ?? "Null Host" as CFString)"
break
case Stream.Event.endEncountered:
outputstream?.close()
outputstream?.remove(from: RunLoop.current, forMode: RunLoopMode.defaultRunLoopMode)
outputstream = nil
break
case Stream.Event.hasBytesAvailable:
Status.text = "Recieving data..."
NSLog("HasBytesAvaible")
var buffer = [UInt8](repeating: 0, count: 4096)
if (aStream == inputstream){
while (inputstream?.hasBytesAvailable)!{
var len = inputstream?.read(&buffer, maxLength: buffer.count)
if(len! > 0){
Status.text = "Collected data..."
var data1 = NSData(bytes: buffer, length: buffer.count)
Status.text = "Converted Data to NSData..."
var str64 = data1.base64EncodedData(options: .lineLength64Characters)
Status.text = "Decode Base64..."
let data: NSData = NSData(base64Encoded: str64 , options: .ignoreUnknownCharacters)!
// turn Decoded String into Data
Status.text = "Turning Base64 data into image..."
let dataImage = UIImage(data: data as Data)
Status.text = "Done"
// pass the data image to image View.:)
Display.image = dataImage
Status.text = "Image Displayed"
}
}
}
break
case Stream.Event.openCompleted:
NSLog("OpenCompleted")
break
case Stream.Event.hasSpaceAvailable:
NSLog("HasSpaceAvailable")
break
default:
print("Unknown event")
}
}
我覺得我應該警告你,在這裏嘗試設備之間的直接連接是非常困難的。當兩臺設備在同一個無線網絡上時,它可能會正常工作,但除此之外......您會遇到很多痛苦。你想解決什麼類型的問題? –
所以我完全理解WiFi並不是非常穩定,你會在這裏分配不一致的東西,但基本上這只是爲了得到一個套接字的概念證明,這樣,一旦我得到了無線網絡的東西,我知道我的路線通過USB連接插座將會容易得多。但基本上我試圖從Android設備每秒發送約4個圖像到iOS設備。然後我需要將消息發送回Android設備,並基本上一遍又一遍地循環播放。這是一個複雜的項目,毫無疑問。謝謝您的幫助! –
不客氣。祝你的項目好運! –