Swift streams and sockets -- help needed

  1. 5 years ago
    Edited 5 years ago by johni

    Hello guys,

    I have couple of minor issues which I couldn't resolve, not after more than 10 hours of searching and reading materials.
    I'm aiming to build an app for some company that needs simple things working, such as: Sockets and Streams.

    With streams, I'm trying to understand how to use NSInputStream read function.
    If I compare this to Java, all I had to do is initialize the InputStream with some kind of source stream to read from, and just use the read method to read 1 byte - simple is that.

    In Swift it's not like that, the read method receives some kind of CMutablePointer object which I know nothing about (couldn't find a satisfiable material about it) and therefore I cannot use it at all.
    If someone could show me a code example writing in Swift language of how to read bytes from an NSInputStream (or any other kind of input stream available in Swift) I'd be really happy.

    Second thing is Sockets.
    Again, if we want to use Sockets in Java, you have to initialize it with remote address and then use the getInputStream and getOutputStream methods to have your infrastructure for communicating with the remote server.
    In Swift, you don't have these simple options, how would you do that instead then?

    I really appreciate any help for solving one of these issues.

  2. niutech

    26 Jul 2014 Administrator

    Tom Lieber replied:

    You can pop this into a Playground to learn about NSInputStream:

    import Cocoa
    // create some data to read
    let data: NSData = "Howdy,
    pardner.".dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion:
    // create a stream that reads the data above
    let stream: NSInputStream = NSInputStream(data: data)
    // begin reading
    var buffer = [UInt8](count: 8, repeatedValue: 0)
    while stream.hasBytesAvailable {
        let result: Int = stream.read(&buffer, maxLength: buffer.count)
        result // the number of bytes read is here
        buffer // the data read is in here

  3. Wow, nice!

    Could you please explain me what does the &buffer mean?
    I'm not familiar with this notation..

    Thank you very much!

  4. Edited 5 years ago by johni

    And also, you'll save me a lot of trouble if you knew how to use Sockets properly like explained in the original post.

    Wow man, the Stream actually works... but I don't know why .


    I do understand now...
    The read method gets a POINTER to a so-called buffer... not the buffer itself (not the array itself).
    Although I thought that Swift passes objects by reference.. and by reference means a pointer to the object... So I still don't get why it was a compile-error to insert "buffer" as a parameter for the CMutablePointer.

    If you know the answer for that I'd be glad to learn some more. ! :)

or Sign Up to reply!