how to use socket in swift (connect, send and get message)
I use the SwiftSocket
https://github.com/swiftsocket/SwiftSocket for TCP
connection. It is easy to use. For example for using it (i add comments to it):
I have my wrapper for work with this lib and this is the method how to send request and get response:
private func blockingRequest(data: String, client: TCPClient?) -> (data: String?, error: ConnectionError?) {
// It use ufter connection
if client != nil {
// Send data
var (isSuccess, errorMessage) = client!.send(str: data)
if isSuccess {
// Read response data
var data = client!.read(1024*10)
if let d = data {
// Create String from response data
if let str = NSString(bytes: d, length: d.count, encoding: NSUTF8StringEncoding) as? String {
return (data: str, error: nil)
} else {
return (data: nil, error: ConnectionError.BadResponseData)
}
} else {
return (data: nil, error: ConnectionError.BadResponseData)
}
} else {
println(errorMessage)
return (data: nil, error: ConnectionError.RequestError)
}
} else {
return (data: nil, error: ConnectionError.RequestError)
}
}