Giter VIP home page Giter VIP logo

swiftwebsocket's Introduction

 SwiftWebSocket

API Docs Swift/5.0 Build Status

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.

Project Status

I'm looking for someone to help with or take over maintenance of this project.

Features

  • High performance.
  • 100% conforms to Autobahn Tests. Including base, limits, compression, etc. Test results.
  • TLS / WSS support. Self-signed certificate option.
  • The API is modeled after the Javascript API.
  • Reads compressed messages (permessage-deflate). RFC 7692
  • Send pings and receive pong events.
  • Strict UTF-8 processing.
  • binaryType property to choose between [UInt8] or NSData messages.
  • Zero asserts. All networking, stream, and protocol errors are routed through the error event.
  • iOS / Objective-C support.

Example

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()
            }
        }
    }
}

Custom Headers

var request = URLRequest(url: URL(string:"ws://url")!)
request.addValue("AUTH_TOKEN", forHTTPHeaderField: "Authorization")
request.addValue("Value", forHTTPHeaderField: "X-Another-Header")
let ws = WebSocket(request: request)

Reuse and Delaying WebSocket Connections

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

Compression

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

Self-signed SSL Certificate

let ws = WebSocket("ws://url")
ws.allowSelfSignedSSL = true

Network Services (VoIP, Video, Background, Voice)

// Allow socket to handle VoIP in the background.
ws.services = [.VoIP, .Background] 

Installation (iOS and OS X)

Add the following to your Cartfile:

github "tidwall/SwiftWebSocket"

Then run carthage update.

Follow the current instructions in Carthage's README for up to date installation instructions.

The import SwiftWebSocket directive is required in order to access SwiftWebSocket features.

Add the following to your Podfile:

use_frameworks!
pod 'SwiftWebSocket'

Then run pod install with CocoaPods 0.36 or newer.

The import SwiftWebSocket directive is required in order to access SwiftWebSocket features.

Manually

Copy the SwiftWebSocket/WebSocket.swift file into your project.
You must also add the libz.dylib library. Project -> Target -> Build Phases -> Link Binary With Libraries

There is no need for import SwiftWebSocket when manually installing.

Contact

Josh Baker @tidwall

License

SwiftWebSocket source code is available under the MIT License.

swiftwebsocket's People

Contributors

abhisheksengar avatar alexkotenko avatar bj97301 avatar danielrhodes avatar ivanbarisic05 avatar marcboeker avatar mlilback avatar ricardopereira avatar sega-zero avatar stas-rmr avatar sumnerevans avatar tidwall avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

swiftwebsocket's Issues

Carthage support: has bitcode disabled

I can't build the framework with Carthage.

Carthage version: 0.14.0
Cartfile: github "tidwall/SwiftWebSocket" ~> 2.5

Partial log:

/usr/bin/xcrun xcodebuild -project /Users/rp/Desktop/AblyExample/Carthage/Checkouts/SwiftWebSocket/SwiftWebSocket.xcodeproj -scheme SwiftWebSocket-tvOS -configuration Release -sdk appletvsimulator ONLY_ACTIVE_ARCH=NO CODE_SIGNING_REQUIRED=NO CODE_SIGN_IDENTITY= clean buildBuild settings from command line:
    CODE_SIGN_IDENTITY =
    CODE_SIGNING_REQUIRED = NO
    ONLY_ACTIVE_ARCH = NO
    SDKROOT = appletvsimulator9.1

=== CLEAN TARGET SwiftWebSocket-tvOS OF PROJECT SwiftWebSocket WITH CONFIGURATION Release ===

Check dependencies
target 'SwiftWebSocket-tvOS' has bitcode disabled (ENABLE_BITCODE = NO), but it is required for the 'appletvos' platform

=== BUILD TARGET SwiftWebSocket-tvOS OF PROJECT SwiftWebSocket WITH CONFIGURATION Release ===

Check dependencies
target 'SwiftWebSocket-tvOS' has bitcode disabled (ENABLE_BITCODE = NO), but it is required for the 'appletvos' platform

NeedMoreInput exception

Hi,
I integrated the lib in my project and just simple tried to create a socket and open (thats it).
I keep receiving NeedMoreInput exception and I have no other error.
I tried for simplicity to use this url:
ws://echo.websocket.org

Throwing line is 1115 in readResponse()

What can be the cause?
Thanks!

abnormal timeout or missing something?

Hello guys,

First of all, thanks a lot for your work, this lib is amazing. I'm contacting you today because I've encountered some timeout issues but I don't know if it's normal or if I'm missing something.

I create the socket like so:
socket = WebSocket(url: url) socket?.delegate = self socket?.open()

When receiving webSocketOpen, I send some data to authenticate my websocket but after 30 seconds, the websocket is closing all by itself.
Do I need to do something to keep it alive? Like ping it every 30s or so? I need to keep it alive in case the server needs to send me text message at any moment (but that can be way longer than 30 seconds after the socket being created).

Thanks a lot for your help guys.

Best regards,

Web socket closes with code 1000 after stream of messages

When a large stream of messages takes longer than ~ 30 seconds to handle, after the last message is received, I get a socket closed message with a code 1000.

If I store the messages to an in-memory datastore, rather than on disk, this dramatically reduces the time it takes to process the messages (around 6 seconds), and this doesn't occur and the connection remains open, communicating normally.

Wondering if you know why this is happening and have any solutions for suggestions/workarounds?

Swift/3.0 fails to build?

I just tried using both Carthage and a manual zip download to build the swift/3.0 branch in Xcode 8b6. As soon as I invoke Build, I get this error:

“Use Legacy Swift Language Version” (SWIFT_VERSION) is required to be configured correctly for targets which use Swift. Use the [Edit > Convert > To Current Swift Syntax…] menu to choose a Swift version or use the Build Settings editor to configure the build setting directly.

I haven't tried to troubleshoot this at all, since it seems something's fundamentally wrong. Am I missing something? Thanks.

Invalid frame length when used with Kodi (aka: XBMC)

I'm noticing my JSON-RPC messages aren't getting processed when I use SwiftWebSocket to send remote control messages to Kodi. The error log for Kodi states the following:

15:49:34 T:4582928384    INFO: WebSocket: Frame with invalid length received
15:49:34 T:4582928384    INFO: WebSocket: Invalid frame received
15:49:34 T:4582928384    INFO: WebSocket: Frame with invalid length received
15:49:34 T:4582928384    INFO: WebSocket: Invalid frame received
15:49:34 T:4582928384    INFO: WebSocket: Fragmented control frame (opcode  9) received
15:49:34 T:4582928384    INFO: WebSocket: Invalid frame received
15:49:34 T:4582928384    INFO: WebSocket: Frame with invalid length received
15:49:34 T:4582928384    INFO: WebSocket: Invalid frame received

It seems to work once occasionally, though. I'm assuming it's some sort of formatting/checksum error on one end of the connection. No unusual config for SwiftWebSocket. BinaryType is .UInt8Array. Any ideas?

Xcode 8 beta 6 build errors

I was trying to use the swift3 branch in Xcode beta 6 and am getting quite a few build errors:

/Pods/SwiftWebSocket/Source/WebSocket.swift:105:25: Function types cannot have argument label 'code'; use '_' instead
/Pods/SwiftWebSocket/Source/WebSocket.swift:105:37: Function types cannot have argument label 'reason'; use '_' instead
/Pods/SwiftWebSocket/Source/WebSocket.swift:105:54: Function types cannot have argument label 'wasClean'; use '_' instead
/Pods/SwiftWebSocket/Source/WebSocket.swift:107:25: Function types cannot have argument label 'error'; use '_' instead
/Pods/SwiftWebSocket/Source/WebSocket.swift:109:27: Function types cannot have argument label 'data'; use '_' instead
/Pods/SwiftWebSocket/Source/WebSocket.swift:111:24: Function types cannot have argument label 'data'; use '_' instead
/Pods/SwiftWebSocket/Source/WebSocket.swift:113:23: Function types cannot have argument label 'code'; use '_' instead
/Pods/SwiftWebSocket/Source/WebSocket.swift:113:35: Function types cannot have argument label 'reason'; use '_' instead
/Pods/SwiftWebSocket/Source/WebSocket.swift:113:52: Function types cannot have argument label 'wasClean'; use '_' instead
/Pods/SwiftWebSocket/Source/WebSocket.swift:113:69: Function types cannot have argument label 'error'; use '_' instead
/Pods/SwiftWebSocket/Source/WebSocket.swift:412:18: Cannot invoke initializer for type 'UnsafeMutablePointer<UInt8>' with an argument list of type '(UnsafeMutableRawPointer!)'
/Pods/SwiftWebSocket/Source/WebSocket.swift:473:18: Cannot invoke initializer for type 'UnsafeMutablePointer<UInt8>' with an argument list of type '(UnsafeMutableRawPointer!)'
/Pods/SwiftWebSocket/Source/WebSocket.swift:679:14: 'NSOutputStream' has been renamed to 'OutputStream'
/Pods/SwiftWebSocket/Source/WebSocket.swift:23:15: Cannot invoke initializer for type 'UnsafeMutablePointer<UInt8>' with an argument list of type '(UnsafeMutableRawPointer!)'
/Pods/SwiftWebSocket/Source/WebSocket.swift:37:23: Cannot invoke initializer for type 'UnsafeMutablePointer<UInt8>' with an argument list of type '(UnsafeMutableRawPointer!)'
/Pods/SwiftWebSocket/Source/WebSocket.swift:64:20: Cannot invoke initializer for type 'UnsafePointer<UInt8>' with an argument list of type '(UnsafeRawPointer)'
/Pods/SwiftWebSocket/Source/WebSocket.swift:90:14: Enum element 'continu' cannot be referenced as an instance member
/Pods/SwiftWebSocket/Source/WebSocket.swift:91:14: Enum element 'text' cannot be referenced as an instance member
/Pods/SwiftWebSocket/Source/WebSocket.swift:92:14: Enum element 'binary' cannot be referenced as an instance member
/Pods/SwiftWebSocket/Source/WebSocket.swift:93:14: Enum element 'close' cannot be referenced as an instance member
/Pods/SwiftWebSocket/Source/WebSocket.swift:94:14: Enum element 'ping' cannot be referenced as an instance member
/Pods/SwiftWebSocket/Source/WebSocket.swift:95:14: Enum element 'pong' cannot be referenced as an instance member
/Pods/SwiftWebSocket/Source/WebSocket.swift:126:14: Enum element 'uInt8Array' cannot be referenced as an instance member
/Pods/SwiftWebSocket/Source/WebSocket.swift:127:14: Enum element 'nsData' cannot be referenced as an instance member
/Pods/SwiftWebSocket/Source/WebSocket.swift:128:14: Enum element 'uInt8UnsafeBufferPointer' cannot be referenced as an instance member
/Pods/SwiftWebSocket/Source/WebSocket.swift:154:14: Enum element 'connecting' cannot be referenced as an instance member
/Pods/SwiftWebSocket/Source/WebSocket.swift:155:14: Enum element 'open' cannot be referenced as an instance member
/Pods/SwiftWebSocket/Source/WebSocket.swift:156:14: Enum element 'closing' cannot be referenced as an instance member
/Pods/SwiftWebSocket/Source/WebSocket.swift:157:14: Enum element 'closed' cannot be referenced as an instance member
/Pods/SwiftWebSocket/Source/WebSocket.swift:247:22: 'append' is unavailable: Replaced by append(_: String)
/Pods/SwiftWebSocket/Source/WebSocket.swift:283:25: Value of optional type 'UnicodeScalar?' not unwrapped; did you mean to use '!' or '?'?
/Pods/SwiftWebSocket/Source/WebSocket.swift:315:58: Cannot invoke initializer for type 'UnsafePointer<UInt8>' with an argument list of type '(UnsafeRawPointer)'
/Pods/SwiftWebSocket/Source/WebSocket.swift:418:112: 'sizeof' is unavailable: use MemoryLayout<T>.size instead.
/Pods/SwiftWebSocket/Source/WebSocket.swift:480:172: 'sizeof' is unavailable: use MemoryLayout<T>.size instead.
/Pods/SwiftWebSocket/Source/WebSocket.swift:490:17: Ambiguous use of 'init'
/Pods/SwiftWebSocket/Source/WebSocket.swift:610:54: 'init(allocatingCapacity:)' is unavailable: use 'UnsafeMutablePointer.allocate(capacity:)'
/Pods/SwiftWebSocket/Source/WebSocket.swift:612:53: 'init(allocatingCapacity:)' is unavailable: use 'UnsafeMutablePointer.allocate(capacity:)'
/Pods/SwiftWebSocket/Source/WebSocket.swift:616:21: Value of type 'DispatchQueue' has no member 'after'
/Pods/SwiftWebSocket/Source/WebSocket.swift:620:21: Value of type 'DispatchQueue' has no member 'after'
/Pods/SwiftWebSocket/Source/WebSocket.swift:762:37: Extraneous argument label 'error:' in call
/Pods/SwiftWebSocket/Source/WebSocket.swift:770:41: Extraneous argument labels 'code:reason:wasClean:' in call
/Pods/SwiftWebSocket/Source/WebSocket.swift:777:35: Extraneous argument labels 'code:reason:wasClean:error:' in call
/Pods/SwiftWebSocket/Source/WebSocket.swift:821:33: Value of type 'DispatchQueue' has no member 'after'
/Pods/SwiftWebSocket/Source/WebSocket.swift:847:71: '?' must be followed by a call, member lookup, or subscript
/Pods/SwiftWebSocket/Source/WebSocket.swift:847:35: Cannot invoke initializer for type 'UnsafeMutablePointer<UInt8>' with an argument list of type '(UnsafeMutableRawPointer!)'
/Pods/SwiftWebSocket/Source/WebSocket.swift:1028:35: Cannot convert value of type 'URL' to expected argument type 'CFURL!'
/Pods/SwiftWebSocket/Source/WebSocket.swift:1047:91: Missing argument label 'options:' in call
/Pods/SwiftWebSocket/Source/WebSocket.swift:1059:41: 'NSOutputStream' has been renamed to 'OutputStream'
/Pods/SwiftWebSocket/Source/WebSocket.swift:1062:53: Cannot convert value of type 'String' to expected argument type 'CFString!'
/Pods/SwiftWebSocket/Source/WebSocket.swift:1069:28: Type 'StreamNetworkServiceTypeValue' has no member 'voip'
/Pods/SwiftWebSocket/Source/WebSocket.swift:1104:59: '?' must be followed by a call, member lookup, or subscript
/Pods/SwiftWebSocket/Source/WebSocket.swift:1104:23: Cannot invoke initializer for type 'UnsafeMutablePointer<UInt8>' with an argument list of type '(UnsafeMutableRawPointer!)'
/Pods/SwiftWebSocket/Source/WebSocket.swift:1117:19: Cannot invoke initializer for type 'UnsafeMutablePointer<UInt8>' with an argument list of type '(UnsafeMutableRawPointer!)'
/Pods/SwiftWebSocket/Source/WebSocket.swift:1373:60: 'init' has been renamed to 'init(mutating:)'
/Pods/SwiftWebSocket/Source/WebSocket.swift:1588:27: 'dirty' is inaccessible due to 'private' protection level
/Pods/SwiftWebSocket/Source/WebSocket.swift:1732:23: Type of expression is ambiguous without more context
/Pods/SwiftWebSocket/Source/WebSocket.swift:1736:23: Type of expression is ambiguous without more context
/Pods/SwiftWebSocket/Source/WebSocket.swift:1740:23: Type of expression is ambiguous without more context
/Pods/SwiftWebSocket/Source/WebSocket.swift:1744:23: Type of expression is ambiguous without more context
/Pods/SwiftWebSocket/Source/WebSocket.swift:1756:9: Argument labels '(request:, subProtocols:)' do not match any available overloads
/Pods/SwiftWebSocket/Source/WebSocket.swift:1805:16: 'id' is inaccessible due to 'private' protection level
/Pods/SwiftWebSocket/Source/WebSocket.swift:1811:22: Use of unresolved identifier 'ws'
/Pods/SwiftWebSocket/Source/WebSocket.swift:1812:15: Use of unresolved identifier 'ws'
/Pods/SwiftWebSocket/Source/WebSocket.swift:1603:45: Call can throw, but it is not marked with 'try' and the error is not handled
/Pods/SwiftWebSocket/Source/WebSocket.swift:1747:17: Method 'open(_:subProtocols:)' with Objective-C selector 'open:subProtocols:' conflicts with previous declaration with the same Objective-C selector
/Pods/SwiftWebSocket/Source/WebSocket.swift:1820:17: Method 'send' with Objective-C selector 'send:' conflicts with previous declaration with the same Objective-C selector
/Pods/SwiftWebSocket/Source/WebSocket.swift:1829:17: Method 'send' with Objective-C selector 'send:' conflicts with previous declaration with the same Objective-C selector

Feature: Can add helper wrapper to this socket

Sometimes, we want to maintain one SwiftWebSocket instance to connect to one URL only. So when current socket opening, if the user wants to reopen it (e.g. switch to connect a new URL), he has to close it first and then in the close event to reopen it. Such operations can have errors and better to implement a wrapper for this. Similar for operations like retry code logic in fail.

Swift 2.2 - Unknown attribute asmname

It seems that on Xcode 7.3b2 and the included Swift 2.2 beta version, the keyword @asmname has been removed so all those methods are generating errors and preventing the build.

@asmname("zlibVersion") private func zlibVersion() -> COpaquePointer
@asmname("deflateInit2_") private func deflateInit2(strm : UnsafeMutablePointer<Void>, level : CInt, method : CInt, windowBits : CInt, memLevel : CInt, strategy : CInt, version : COpaquePointer, stream_size : CInt) -> CInt
@asmname("deflateInit_") private func deflateInit(strm : UnsafeMutablePointer<Void>, level : CInt, version : COpaquePointer, stream_size : CInt) -> CInt
@asmname("deflateEnd") private func deflateEnd(strm : UnsafeMutablePointer<Void>) -> CInt
@asmname("deflate") private func deflate(strm : UnsafeMutablePointer<Void>, flush : CInt) -> CInt
@asmname("inflateInit2_") private func inflateInit2(strm : UnsafeMutablePointer<Void>, windowBits : CInt, version : COpaquePointer, stream_size : CInt) -> CInt
@asmname("inflateInit_") private func inflateInit(strm : UnsafeMutablePointer<Void>, version : COpaquePointer, stream_size : CInt) -> CInt
@asmname("inflate") private func inflateG(strm : UnsafeMutablePointer<Void>, flush : CInt) -> CInt
@asmname("inflateEnd") private func inflateEndG(strm : UnsafeMutablePointer<Void>) -> CInt

sluggish performance after reconnecting for a couple of times

I have a ViewController in which I'm using the WebSocket.
there is also a UITableView in myViewController.
I only initialize the WebSocket once, and then close and open if needed.
but every time I close the WebSocket, and open it again(without re creating any object) the tableView gets more sluggish. as if after 5 times it gets really slow.
the cpu doesn't show anything and ram usage is normal.
but still everything is super slow, even the OS it self
I'm using ipad mini2 and iOS 9.3
any guess what this could be?

Reconnect timeout

When I try to turn off wifi and turn on
I will start a timer to detect network connection and try to reconnect socket with socket.open()

sometimes works but sometimes I got timeout after long time
but I try to use browser websocket to connect my server it works fine

any idea?

Cannot use my own origin for websocket

Hi @tidwall

Thanks a lot for such a great library. But I have an issue.

I want to use my own custom origin for connection request like this:

let mutableRequest = NSMutableURLRequest(URL: "my socket url")
mutableRequest.addValue("my value", forHTTPHeaderField: "cookie")
mutableRequest.addValue("my value", forHTTPHeaderField: "origin")

socket.open(request: mutableRequest)

It's important for test purpose. We have dev and production servers.

But as I can see in private InnerWebSocket class:

req.setValue(req.URL!.absoluteString, forHTTPHeaderField: "Origin")

you always use Origin from the request that I've provided to make a connection.

So in that case we just can't organise our test environment.
It would be great if you add some if statement for the Origin http field, if there is something that user provided, otherwise set Origin from the request url.

Thanks a lot!

Reconnect sample doesn't actually reconnect.

assuming the following code to reconnect on close:

let ws = WebSocket()
ws.event.close = { _ in
    ws.open()                 // reopen the socket to the previous url
}
ws.open("ws://url") // call with url

The inner ws.open() will return immediately as the internal opened flag is still true.

My current workaround is, calling close prior to calling open.

let ws = WebSocket()
ws.event.close = { _ in
    ws.close()
    ws.open()                 // reopen the socket to the previous url
}
ws.open("ws://url") // call with url

Is this the expected behavior?

Doesn't work in playground due to zlib code

When I include WebSocket.swift in a playground's sources directory, the playground fails to execute.

I'm able to work around the failure by commenting out the @_silgen_name declarations for libz methods and the uses of those methods in the Inflator/Deflator classes.

I'm not sure what the real solution to the problem is. Maybe using Apple's libcompression API, but I haven't (yet) taken the time to compare it to libz.

Getting streamStatus.atEnd when connecting to web socket server under SSL

Hello,

I have created the NodeJs project to host a server:

`
var fs = require('fs');
var https = require('https');

var express = require('express');
var app = express();

// Preparing for HTTPS hosting (This is not a self signed certificate and it is green on chrome)
var sslDir = '/home/wolney/Applications/ssl/'
var privateKey = fs.readFileSync(sslDir+'server.key');
var certificate = fs.readFileSync(sslDir+'server.crt');
var certificateAuthority = fs.readFileSync(sslDir+'sub.class1.server.ca.pem');

var credentials = {key: privateKey, cert: certificate, ca: certificateAuthority};

var serverPort = 443;

var server = https.createServer(credentials, app);
var io = require('socket.io')(server);

app.get('/', function(req, res) {
res.sendFile(__dirname + '/public/index.html');
});

io.on('connection', function(socket) {
console.log('new connection');
socket.emit('message', 'This is a message from the dark side.');
});

server.listen(serverPort, function() {
console.log('server up and running at %s port', serverPort);
});
`
public/index.html is:

`
<!doctype html>

I am alive!!

<script src="https://cdnjs.cloudflare.com/ajax/libs/socket.io/1.3.5/socket.io.js"></script> <script> var URL_SERVER = 'https://apex5associates.com:443'; var socket = io.connect(URL_SERVER); socket.on('message', function(data) { alert(data); }); </script> `

It woks fine when using the browser in the browser.

However when I try to access via my app running in the simulator I get error event with Network(streamStatus.atEnd). The code I am using was copied from the sample:

`
func echoTest(){
let request = NSMutableURLRequest(URL: NSURL(string:"wss://apex5associates.com:443")!)
let ws = WebSocket(request: request)

    var messageNum = 0
    let send : ()->() = {
        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()
            }
        }
    }
}

`

Any idea on what I doing wrong?

Thanks in advance

build fail

With last XCode (for iOS9), I have the following build error (carthage update) :

The following build commands failed:
CompileSwift normal x86_64 /Library/WebServer/Documents/everquity/iOs/everquity/Carthage/Checkouts/SwiftWebSocket/Source/WebSocket.swift
CompileSwiftSources normal x86_64 com.apple.xcode.tools.swift.compiler
(2 failures)
/Library/WebServer/Documents/everquity/iOs/everquity/Carthage/Checkouts/SwiftWebSocket/Source/WebSocket.swift:622:30: error: 'join' is unavailable: call the 'joinWithSeparator()' method on the sequence of elements
/Library/WebServer/Documents/everquity/iOs/everquity/Carthage/Checkouts/SwiftWebSocket/Source/WebSocket.swift:659:50: error: 'array' is unavailable: please construct an Array from your lazy sequence: Array(...)
A shell task failed with exit code 65:
** BUILD FAILED **


The following build commands failed:
CompileSwift normal x86_64 /Library/WebServer/Documents/everquity/iOs/everquity/Carthage/Checkouts/SwiftWebSocket/Source/WebSocket.swift
 CompileSwiftSources normal x86_64 com.apple.xcode.tools.swift.compiler
(2 failures)

Swift 3 error with unicode characters

Hi! I am using your library to build an app for a NodeBB forum. All have been working fine until i updated it to use Swift 3. Now, I cant parse the JSON text messages that the server sends me.

An example of the messages (it isnt a complete message):

{"topics":[{"tid":24909,"uid":400,"cid":"3","mainPid":790889,"title":"Retrasados just being retrasados una vez mOptional("\u{00E1}")s en Galicia","slug":"24909/retrasados-just-being-retrasados-una-vez-mOptional("\u{00E1}")s-en-galicia","timestamp":1473334344094,"lastposttime":1473414364688,"postcount":23,"viewcount":95,"locked":false,"deleted":false,"pinned":false,"teaserPid":"791474","titleRaw":"Retrasados just being retrasados una vez mOptional("\u{00E1}")s en Galicia"}]}

As you can see, there are multiple Optional("\u{????}") in the text message. When I try to use JSONSerialization.jsonObject to parse the JSON message, it gives me the error:

Error Domain=NSCocoaErrorDomain Code=3840 "Badly formed object around character 122." UserInfo={NSDebugDescription=Badly formed object around character 122.}

I am not totally sure if the problem is in your library.

Thank you! :)

Question: Reconnect.

If for example app goes to background and goes to foreground, and you would like to reconnect to server, then what would be the best approach?

From what I gather, I need to create a new socket object with new event handlers. Is that correct?

If the above approach is correct, then I would respectfully suggest the following:
Make it possible to create a WebSocket instance without connecting right away. And then being able to ws.close and ws.open on that same object, and reuse the already added eventhandlers.

With this it will also be possible to add eventhandlers and setup other stuff before you actually try to connect to the server. This would be practical to me at least :-)

WatchOS support

Why is WatchOS not supported? Are there any limitations on WatchOS that prevent us from using web sockets on the Apple Watch?

No websocket close event

I am using the 1.2 branch and everything seems to work well except I do not receive an event when there is a server disconnection

websocket.event.close = { (code, reason, clean) in
println("web server socket close")
}

event.message, event.open are working.

Release websocket instances when it hasn't connected yet.

This is somewhat related to #14, which a solution to might apply here also.

When experimenting with bad network conditions, where a 100% packet loss is enforced, it seems that if I create a new WebSocket that hence can't connect to the server and try to close this instance, then it will be retained, including the event handlers.
At least until the underlying NSURLRequest times out.

Using something along the lines of the below code will give me these results:
If network is connected, I will end up with 1 websocket instance.
If there is 100% packet loss, I will end up with 3 instances.

var ws = WebSocket("wss://echo.websocket.org")
func echoTest() {
  ws.close()
  ws = WebSocket("wss://echo.websocket.org")
  ws.close()
  ws = WebSocket("wss://echo.websocket.org")
}

iOS9 Ready

Is SwfitWebSocket ready for iOS9 and App Transport Security?

socket header

socket?.event.header = { message in
}

I was reading socket header with following code, but in new version socket event doesn't have header field. So what is the new way to read header?

Building for watchOS2 beta6

I manually added the files and getting:
WebSocket.swift:622:26: '[String]' does not have a member named 'joinWithSeparator'

2.6 Doesn't Build with Carthage

GIves the laconic error message:

** BUILD FAILED **


The following build commands failed:
    CompileSwift normal arm64 /Users/peter/Dropbox/Development/Programming/Swift/SwiftDDP/Carthage/Checkouts/SwiftWebSocket/Source/WebSocket.swift
    CompileSwiftSources normal arm64 com.apple.xcode.tools.swift.compiler
(2 failures)
A shell task failed with exit code 65:
** BUILD FAILED **


The following build commands failed:
    CompileSwift normal arm64 /Users/peter/Dropbox/Development/Programming/Swift/SwiftDDP/Carthage/Checkouts/SwiftWebSocket/Source/WebSocket.swift
    CompileSwiftSources normal arm64 com.apple.xcode.tools.swift.compiler
(2 failures)

dead lock in main queue

When I use NSCondition or dispatch_semaphore_wait in main_queue for WebSocket response, I have dead lock.

The problem looks like....

WebSocket.swift:
594: dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 0), dispatch_get_main_queue()){
595: manager.add(self)
596: }

Header field name keys case-sensitivity

Hi - While enabling compression, I noticed that the keys "Sec-Websocket-SubProtocol" and "Sec-Websocket-Extensions" are switched on without testing the case of the string.

I couldn't find any reference in the RFC protocol anything that was overly clear regarding case sensitivity in the header string, but it does appear that the NSURLRequestClass Reference indicates these field names should be case-insensitive.

In the below snippet

func readResponse() throws {
....
    switch key {
        case ("Sec-WebSocket-SubProtocol"):
            privateSubProtocol = value
        case ("Sec-WebSocket-Extensions"):
            let parts = value.componentsSeparatedByString(";")
...
}

I think this should probably be sanitized either:

func readResponse() throws {
....
    if (key.caseInsensitiveCompare("Sec-WebSocket-SubProtocol") == .OrderedSame) {
        privateSubProtocol = value
    } else if (key.caseInsensitiveCompare("Sec-WebSocket-Extensions") == .OrderedSame) {
        let parts = value.componentsSeparatedByString(";")
...
}

or:

func readResponse() throws {
....
    switch key.lowercaseString {
        case ("Sec-WebSocket-SubProtocol").lowercaseString:
            privateSubProtocol = value
        case ("Sec-WebSocket-Extensions").lowercaseString:
            let parts = value.componentsSeparatedByString(";")

...
}

I'm unsure if there are other areas which may require a similar update, just raising to your attention.

Use [weak self] instead of [unowned self]

App crashes:
screen shot 2016-08-15 at 12 18 52

I'm recreating new WebSocket instance in :func webSocketError(error: NSError)or func webSocketClose(code: Int, reason: String, wasClean: Bool).

Looks like, there is no guarantee that WebSocket will exist, when closure will be called.

Version: 2.6.1.

I will let you know if I catch same error on 2.6.3

Automated Tests

Add automation for the Autobahn tests prior to each tagged release.

Require

  • Autobahn test script
  • Autobahn test reports stay updated and are linked from README
  • Test-ObjectiveC Xcode unit test

Possible solutions

  • CI service like TravisCI or CircleCI.
  • Using Cocoapods for adding a bash script to the pod lib lint pipeline.

Cannot receive pong with event handler

I've implemented my pong event handler like so

      self.socket.event.pong {
            print("PONG")
            self.dm.pongReceived = true
        }

except whenever I send a pong to this swift client, PONG is never printed to the console and thus, the event handler is never called. Is there anything I can do to fix this? I'm fairly sure my server is sending pongs correctly.

Abnormal Closure - code 1006

After a few minutes he closes the connection giving the error "Abnormal Closure" (code 1006), someone knows what can be?
When I used socket rocket in objective-c worked

Crash when resuming app from background

Hello I have a crash each time the user is on a socket related view and the App is on the background for a long time. When the App resumes it crashes.
Any idea what causes this? I'm using Python for Backend with wss protocol.

libsystem_kernel​.dylib   
__psynch_cvwait
1   WebSocket.swift ​Line ​1616
(Manager in _A42D883B1EA5865CEB62599B0B6EDEEA).(init() -> (Manager in _A42D883B1EA5865CEB62599B0B6EDEEA)).(closure #1)

        let v1 = Int(tv.tv_usec * 1000)
        let v2 = Int(1000 * 1000 * Int(timeInMs % 1000))
        ts.tv_nsec = v1 + v2;
        ts.tv_sec += ts.tv_nsec / (1000 * 1000 * 1000);
        ts.tv_nsec %= (1000 * 1000 * 1000);
        return pthread_cond_timedwait(&self.cond, &self.mutex, &ts)
    }
    func signal(){
        pthread_mutex_lock(&mutex)
        pthread_cond_signal(&cond)
        pthread_mutex_unlock(&mutex)

2   libdispatch​.dylib    
_dispatch_call_block_and_release
3   libdispatch​.dylib    
_dispatch_client_callout
4   libdispatch​.dylib    
_dispatch_queue_drain
5   libdispatch​.dylib    
_dispatch_queue_invoke
6   libdispatch​.dylib    
_dispatch_client_callout
7   libdispatch​.dylib    
_dispatch_root_queue_drain
8   libdispatch​.dylib    
_dispatch_worker_thread3
9   libsystem_pthread​.dylib  
_pthread_wqthread
10  libsystem_pthread​.dylib  
start_wqthread

Receive buffer grows in size

When receiving a high-speed stream of data over the WebSocket the receive buffer keeps realloc'ing an ever larger buffer because the message events cannot be dealt with fast enough. It would be useful if you could instruct the WebSocket to pop the last message and discard all buffered messages or set a maximum number of buffered messages.

Can't get close code

Hi there,

Many thanks for writing such a great library!

We were using the swift 1.2 version of your library and have recently updated to swift 2.1. I am using your swift 2.1 library but when our server sends a certain close code (4000-4016) your library seems to spit out 0. Is this normal?

Any help would be greatly appreciated.

Cheers,
Gavin

TLS: Having trouble connecting.

Modifying your Go test server to serve TLS like this:

err := http.ListenAndServeTLS(":6789", "ssl/server.crt", "ssl/server.key", nil)
    if err != nil {
        log.Fatal("ListenAndServe: ", err)
    }

Connecting with this ur:l "wss://localhost:6789/echo"

Will give this error on the server-side, and the client can't connect:
TLS handshake error from [::1]:58856: tls: first record does not look like a TLS handshake

As you show in your example, there is no issues in connecting to "wss://echo.websocket.org".

The certificates I'm using are self-signed. Might this be causing the issue?
For reference, the modified server works when using Starscream with selfSignedSSL property set to true.

1007 invalid payload size for control frame

Getting such error on communication with server. Seems related to network issues (response form server is > 200msec). Connection is established but data from server is not returned via web socket. Wrong frame begins with byte 0x81

Swift 2.2 Compile errors

I just updated to XCode 7.3 and Swift 2.2 and I'm getting a lot of unknown attribute errors in the following

@asmname("zlibVersion") private func zlibVersion() -> COpaquePointer @asmname("deflateInit2_") private func deflateInit2(strm : UnsafeMutablePointer<Void>, level : CInt, method : CInt, windowBits : CInt, memLevel : CInt, strategy : CInt, version : COpaquePointer, stream_size : CInt) -> CInt @asmname("deflateInit_") private func deflateInit(strm : UnsafeMutablePointer<Void>, level : CInt, version : COpaquePointer, stream_size : CInt) -> CInt @asmname("deflateEnd") private func deflateEnd(strm : UnsafeMutablePointer<Void>) -> CInt @asmname("deflate") private func deflate(strm : UnsafeMutablePointer<Void>, flush : CInt) -> CInt @asmname("inflateInit2_") private func inflateInit2(strm : UnsafeMutablePointer<Void>, windowBits : CInt, version : COpaquePointer, stream_size : CInt) -> CInt @asmname("inflateInit_") private func inflateInit(strm : UnsafeMutablePointer<Void>, version : COpaquePointer, stream_size : CInt) -> CInt @asmname("inflate") private func inflateG(strm : UnsafeMutablePointer<Void>, flush : CInt) -> CInt @asmname("inflateEnd") private func inflateEndG(strm : UnsafeMutablePointer<Void>) -> CInt

Add OS X 10.9 support

NSStream.getStreamsToHostWithName needs to be repl. w/ getStreamsToHost:port
Podspec needs 10.9 min requirement.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.