Using sockets in Swift like in Java

前端 未结 1 1517
闹比i
闹比i 2020-12-23 23:38

If I wanted to connect to a server, in Java I would open a Socket and initialize it with port and host address, then retrieve the input/output streams and read/write whateve

相关标签:
1条回答
  • 2020-12-24 00:04

    I have figured it myself, for those who look for an explanation read ahead;

    There are multiple ways of using Sockets to communicate with local application or a remote server.

    The problem described in the original post was to get the Input/Output streams and get them to work. (At the end of this post there's a reference to another post of mine explaining how to use those streams)

    The NSStream class has a static method (class function in swift) called getStreamsToHost. All you have to prepare is a NSHost objected initialized with a real host address, a port number, a reference to a NSInputStream obj and also for a NSOutputStream obj. Then, you can use the streams as shown here and explained in the reference post.

    look at this simple code;

    let addr = "127.0.0.1"
    let port = 4000
    
    var host :NSHost = NSHost(address: addr)
    var inp :NSInputStream?
    var out :NSOutputStream?
    
    NSStream.getStreamsToHost(host, 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)
    }
    
    // buffer is a UInt8 array containing bytes of the string "Jonathan Yaniv.".
    outputStream.write(&buffer, maxLength: buffer.count)
    

    Before executing this simple code, I launched ncat to listen on port 4000 in my terminal and typed "Hello !" and left the socket opened for communication.

    Jonathans-MacBook-Air:~ johni$ ncat -l 4000
    Hello !
    Jonathan Yaniv.
    Jonathans-MacBook-Air:~ johni$ 
    

    After launching the code, you can see that I have received the string "Jonathan Yaniv.\n" to the terminal before the socket was closed.

    I hope this saved some headache to some of you. If you have more questions give it a shot, I hope I'll be able to answer it.

    The & notation is explained in this post. (Reference to NSInputStream read use)

    0 讨论(0)
提交回复
热议问题