TestsTested | ✗ |
LangLanguage | SwiftSwift |
License | Custom |
ReleasedLast Release | Feb 2018 |
SPMSupports SPM | ✓ |
Maintained by Josh Baker.
Conforming WebSocket (RFC 6455) client library for iOS and Mac OSX.
SwiftWebSocket passes all 521 of the Autobahn’s fuzzing tests, including strict UTF-8, and message compression.
permessage-deflate
). RFC 7692 binaryType
property to choose between [UInt8]
or NSData
messages.error
event.func echoTest(){
var messageNum = 0
let ws = WebSocket("wss://echo.websocket.org")
let send : ()->() = {
messageNum += 1
let msg = "\(messageNum): \(NSDate().description)"
print("send: \(msg)")
ws.send(msg)
}
ws.event.open = {
print("opened")
send()
}
ws.event.close = { code, reason, clean in
print("close")
}
ws.event.error = { error in
print("error \(error)")
}
ws.event.message = { message in
if let text = message as? String {
print("recv: \(text)")
if messageNum == 10 {
ws.close()
} else {
send()
}
}
}
}
let request = NSMutableURLRequest(URL: NSURL(string:"ws://url")!)
request.addValue("AUTH_TOKEN", forHTTPHeaderField: "Authorization")
request.addValue("Value", forHTTPHeaderField: "X-Another-Header")
let ws = WebSocket(request: request)
v2.3.0+ makes available an optional open
method. This will allow for a WebSocket
object to be instantiated without an immediate connection to the server. It can also be used to reconnect to a server following the close
event.
For example,
let ws = WebSocket()
ws.event.close = { _ in
ws.open() // reopen the socket to the previous url
ws.open("ws://otherurl") // or, reopen the socket to a new url
}
ws.open("ws://url") // call with url
The compression
flag may be used to request compressed messages from the server. If the server does not support or accept the request, then connection will continue as normal, but with uncompressed messages.
let ws = WebSocket("ws://url")
ws.compression.on = true
let ws = WebSocket("ws://url")
ws.allowSelfSignedSSL = true
// Allow socket to handle VoIP in the background.
ws.services = [.VoIP, .Background]
Josh Baker @tidwall
SwiftWebSocket source code is available under the MIT License.