Closing a connection

Hello,


I am writing an app that connects to a Java-Server.


Declarations at the top of the class:

let ip = "192.168.1.130"
let port = 3333
var inputStream: NSInputStream?
var outputStream: NSOutputStream?


I use this code to connect to the server:

func connect() {
     NSStream.getStreamsToHostWithName(ip, port: port, inputStream: &inputStream, outputStream: &outputStream)
  
     inputStream!.delegate = self
     outputStream!.delegate = self
  
     inputStream!.scheduleInRunLoop(NSRunLoop.currentRunLoop(), forMode: NSDefaultRunLoopMode)
     outputStream!.scheduleInRunLoop(NSRunLoop.currentRunLoop(), forMode: NSDefaultRunLoopMode)
  
     inputStream!.open()
     outputStream!.open()
}


and this to disconnect:

func disconnect() {
     inputStream?.close()
     outputStream?.close()

     inputStream?.removeFromRunLoop(NSRunLoop.currentRunLoop(), forMode: NSDefaultRunLoopMode)
     outputStream?.removeFromRunLoop(NSRunLoop.currentRunLoop(), forMode: NSDefaultRunLoopMode)

     inputStream = nil
     outputStream = nil
}


connect() is called when the user taps on the connect button

disconnect() is called when the events .ErrorOccurred and .EndEncountered happen or the user taps on the disconnect button.


But the socket seems not be closed because the Java-Server still shows it as open and connected.


In Java i would call

socket.close();


Is there a similar method for iOS?


Thanks in advance!

Calling

-close
on both the input and output streams should be sufficient to close the streams. I just tested this with a small test app here in my office and it works as expected. Some things to watch out for in your code:
  • make sure that

    -disconnect
    is actually called — It's easy to confirm this in the debugger.
  • make sure that

    -disconnect
    is called on the correct thread — In general it's best to confine your access to a input/output stream pair to one thread. I suspect that you call both
    -connect
    and
    -disconnect
    from the main thread, so that's not a problem here.
  • make sure that

    inputStream
    is not nil at the time you call
    -close
    — Because you're using the "?" operator, if
    inputStream
    was nil your entire -disconnect method would be a no-op.

Share and Enjoy

Quinn "The Eskimo!"
Apple Developer Relations, Developer Technical Support, Core OS/Hardware

let myEmail = "eskimo" + "1" + "@apple.com"
Closing a connection
 
 
Q