Using sockets in Swift like in Java

爱⌒轻易说出口 提交于 2019-11-29 21:57:05
johni

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)

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!