How to read a string in tcp juice in Swift

If I have a java tcp server sending some text, how can I read this text from NSInputStreamand save it in a string?

Here is a piece of code that I have, but I'm not sure how to get a line from here:

NSStream.getStreamsToHostWithName(addr, port: port, inputStream: &inp, outputStream: &out)

let inputStream = inp!
let outputStream = out!
inputStream.open()
outputStream.open()

var readByte :UInt8 = 0
while inputStream.hasBytesAvailable {
    inputStream.read(&readByte, maxLength: 1)
}
+4
source share
2 answers

Look at these awesome libraries, they will save your life.

Swift: Starscream

Objective-C: Jetfire SocketRocket

-1
source

1 . , , :

NSStream.getStreamsToHostWithName(addr, port: port, inputStream: &inputStream, outputStream: &outputStream)
inputStream!.open()
outputStream!.open()

let queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)
dispatch_async(queue) {
    let bufferSize = 1024
    var inputBuffer = Array<UInt8>(count:bufferSize, repeatedValue: 0)
    while true {
        let bytesRead = self.inputStream!.read(&inputBuffer, maxLength: bufferSize)

        // Here get string from byte Array
        let responseString = NSString(bytes: inputBuffer, length: inputBuffer.count, encoding: NSUTF8StringEncoding) as! String
        println("Data from Stream = \(responseString)")
    }
}

:

let responseString = NSString(bytes: inputBuffer, length: inputBuffer.count, encoding: NSUTF8StringEncoding) as! String

String

+4

Source: https://habr.com/ru/post/1614873/


All Articles