3

I'm trying to make a socket server application in Swift for iOS. I found this great example:

    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("Hello", maxLength: "Hello".length)

I tried to run the code in XCode and it said that NSHost didn't exist. I Googled it and I found that NSHost wasn't able for iOS. What can I use instead?

Edit

I'm now using Cocoa Async Socket for socket connections. You can find it here CocoaAsyncScket

Shruti Thombre
  • 989
  • 4
  • 11
  • 27
ntoonio
  • 3,024
  • 4
  • 24
  • 28
  • You should probably use CFHostRef from CFNetwork and if you wish to do socket communication, I would reference you the tutorial http://www.raywenderlich.com/3932/networking-tutorial-for-ios-how-to-create-a-socket-based-iphone-app-and-server. – Sandeep Sep 21 '14 at 20:34

2 Answers2

2

Change getStreamsToHost to getStreamsToHostWithName

Change:

NSStream.getStreamsToHost(host, port: port, inputStream: &inp, outputStream: &out)

to

NSStream.getStreamsToHostWithName(addr, port: port, inputStream: &inp, outputStream: &out)
0
var server = "127.0.0.1"
var port = 4000
//var host :NSHost = NSHost(address: server)
var inp :NSInputStream?
var out :NSOutputStream?
NSStream.getStreamsToHostWithName(server, port: port, inputStream: &inp, outputStream: &out)
let inputStream = inp!
let outputStream = out!
inputStream.open()
defer {
    inputStream.close()
}
outputStream.open()
defer {
    outputStream.close()
}
// do stuff here