• Stars
    star
    8,118
  • Rank 4,344 (Top 0.09 %)
  • Language
    Swift
  • License
    Apache License 2.0
  • Created almost 10 years ago
  • Updated 23 days ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

Websockets in swift for iOS and OSX

starscream

Starscream is a conforming WebSocket (RFC 6455) library in Swift.

Features

  • Conforms to all of the base Autobahn test suite.
  • Nonblocking. Everything happens in the background, thanks to GCD.
  • TLS/WSS support.
  • Compression Extensions support (RFC 7692)

Import the framework

First thing is to import the framework. See the Installation instructions on how to add the framework to your project.

import Starscream

Connect to the WebSocket Server

Once imported, you can open a connection to your WebSocket server. Note that socket is probably best as a property, so it doesn't get deallocated right after being setup.

var request = URLRequest(url: URL(string: "http://localhost:8080")!)
request.timeoutInterval = 5
socket = WebSocket(request: request)
socket.delegate = self
socket.connect()

After you are connected, there is either a delegate or closure you can use for process WebSocket events.

Receiving data from a WebSocket

didReceive receives all the WebSocket events in a single easy to handle enum.

func didReceive(event: WebSocketEvent, client: WebSocket) {
	switch event {
	case .connected(let headers):
		isConnected = true
		print("websocket is connected: \(headers)")
	case .disconnected(let reason, let code):
		isConnected = false
		print("websocket is disconnected: \(reason) with code: \(code)")
	case .text(let string):
		print("Received text: \(string)")
	case .binary(let data):
		print("Received data: \(data.count)")
	case .ping(_):
		break
	case .pong(_):
		break
	case .viabilityChanged(_):
		break
	case .reconnectSuggested(_):
		break
	case .cancelled:
		isConnected = false
	case .error(let error):
		isConnected = false
		handleError(error)
        case .peerClosed:
               break
	}
}

The closure of this would be:

socket.onEvent = { event in
	switch event {
		// handle events just like above...
	}
}

Writing to a WebSocket

write a binary frame

The writeData method gives you a simple way to send Data (binary) data to the server.

socket.write(data: data) //write some Data over the socket!

write a string frame

The writeString method is the same as writeData, but sends text/string.

socket.write(string: "Hi Server!") //example on how to write text over the socket!

write a ping frame

The writePing method is the same as write, but sends a ping control frame.

socket.write(ping: Data()) //example on how to write a ping control frame over the socket!

write a pong frame

the writePong method is the same as writePing, but sends a pong control frame.

socket.write(pong: Data()) //example on how to write a pong control frame over the socket!

Starscream will automatically respond to incoming ping control frames so you do not need to manually send pongs.

However if for some reason you need to control this process you can turn off the automatic ping response by disabling respondToPingWithPong.

socket.respondToPingWithPong = false //Do not automaticaly respond to incoming pings with pongs.

In most cases you will not need to do this.

disconnect

The disconnect method does what you would expect and closes the socket.

socket.disconnect()

The disconnect method can also send a custom close code if desired.

socket.disconnect(closeCode: CloseCode.normal.rawValue)

Custom Headers, Protocols and Timeout

You can override the default websocket headers, add your own custom ones and set a timeout:

var request = URLRequest(url: URL(string: "ws://localhost:8080/")!)
request.timeoutInterval = 5 // Sets the timeout for the connection
request.setValue("someother protocols", forHTTPHeaderField: "Sec-WebSocket-Protocol")
request.setValue("14", forHTTPHeaderField: "Sec-WebSocket-Version")
request.setValue("chat,superchat", forHTTPHeaderField: "Sec-WebSocket-Protocol")
request.setValue("Everything is Awesome!", forHTTPHeaderField: "My-Awesome-Header")
let socket = WebSocket(request: request)

SSL Pinning

SSL Pinning is also supported in Starscream.

Allow Self-signed certificates:

var request = URLRequest(url: URL(string: "ws://localhost:8080/")!)
let pinner = FoundationSecurity(allowSelfSigned: true) // don't validate SSL certificates
let socket = WebSocket(request: request, certPinner: pinner)

TODO: Update docs on how to load certificates and public keys into an app bundle, use the builtin pinner and TrustKit.

Compression Extensions

Compression Extensions (RFC 7692) is supported in Starscream. Compression is enabled by default, however compression will only be used if it is supported by the server as well. You may enable compression by adding a compressionHandler:

var request = URLRequest(url: URL(string: "ws://localhost:8080/")!)
let compression = WSCompression()
let socket = WebSocket(request: request, compressionHandler: compression)

Compression should be disabled if your application is transmitting already-compressed, random, or other uncompressable data.

Custom Queue

A custom queue can be specified when delegate methods are called. By default DispatchQueue.main is used, thus making all delegate methods calls run on the main thread. It is important to note that all WebSocket processing is done on a background thread, only the delegate method calls are changed when modifying the queue. The actual processing is always on a background thread and will not pause your app.

socket = WebSocket(url: URL(string: "ws://localhost:8080/")!, protocols: ["chat","superchat"])
//create a custom queue
socket.callbackQueue = DispatchQueue(label: "com.vluxe.starscream.myapp")

Example Project

Check out the SimpleTest project in the examples directory to see how to setup a simple connection to a WebSocket server.

Requirements

Starscream works with iOS 8/10.10 or above for CocoaPods/framework support. To use Starscream with a project targeting iOS 7, you must include all Swift files directly in your project.

Installation

Swift Package Manager

The Swift Package Manager is a tool for automating the distribution of Swift code and is integrated into the swift compiler.

Once you have your Swift package set up, adding Starscream as a dependency is as easy as adding it to the dependencies value of your Package.swift.

dependencies: [
    .package(url: "https://github.com/daltoniam/Starscream.git", from: "4.0.6")
]

CocoaPods

Check out Get Started tab on cocoapods.org.

To use Starscream in your project add the following 'Podfile' to your project

source 'https://github.com/CocoaPods/Specs.git'
platform :ios, '12.0'
use_frameworks!

pod 'Starscream', '~> 4.0.6'

Then run:

pod install

Carthage

Check out the Carthage docs on how to add a install. The Starscream framework is already setup with shared schemes.

Carthage Install

You can install Carthage with Homebrew using the following command:

$ brew update
$ brew install carthage

To integrate Starscream into your Xcode project using Carthage, specify it in your Cartfile:

github "daltoniam/Starscream" >= 4.0.6

Other

Simply grab the framework (either via git submodule or another package manager).

Add the Starscream.xcodeproj to your Xcode project. Once that is complete, in your "Build Phases" add the Starscream.framework to your "Link Binary with Libraries" phase.

Add Copy Frameworks Phase

If you are running this in an OSX app or on a physical iOS device you will need to make sure you add the Starscream.framework to be included in your app bundle. To do this, in Xcode, navigate to the target configuration window by clicking on the blue project icon, and selecting the application target under the "Targets" heading in the sidebar. In the tab bar at the top of that window, open the "Build Phases" panel. Expand the "Link Binary with Libraries" group, and add Starscream.framework. Click on the + button at the top left of the panel and select "New Copy Files Phase". Rename this new phase to "Copy Frameworks", set the "Destination" to "Frameworks", and add Starscream.framework respectively.

TODOs

  • Proxy support
  • Thread safe implementation
  • Better testing/CI
  • SSL Pinning/client auth examples

License

Starscream is licensed under the Apache v2 License.

Contact

Dalton Cherry

Austin Cherry

More Repositories

1

SwiftHTTP

Thin wrapper around NSURLSession in swift. Simplifies HTTP requests.
Swift
1,880
star
2

DCAnimationKit

A collection of animations for iOS. Simple, just add water animations.
Objective-C
799
star
3

JSONJoy-Swift

Convert JSON to Swift objects.
Swift
354
star
4

Skeets

Fetch, cache, and display images via HTTP in Swift.
Swift
191
star
5

bumblebee

Abstract text processing and pattern matching engine in Swift. Converts text into NSAttributedStrings. Builtin markdown support.
Swift
108
star
6

tarkit

untar and tar files on iOS and OS X. Also supports gzip tars.
Objective-C
88
star
7

SwiftLog

Simple and easy logging in Swift.
Swift
73
star
8

UICustomizeKit

Base UIKit components extended to allow almost any customizations. Comes with Bootstrap and Flat UIs out of the box.
Objective-C
68
star
9

JSONJoy

Makes JSON a joy to use
Objective-C
56
star
10

FontAwesome-iOS

Provides easy access to font Awesome icons in iOS
Objective-C
46
star
11

DCLabel

Convert markdown or html text with embed content into a label.
Objective-C
31
star
12

DCCommentView

Comment view for iOS, same as messages app. Customizable.
Objective-C
30
star
13

Jazz

Easier layer animations in Swift
Swift
25
star
14

DCTextEngine

An engine that convert text to attributed strings and attributed strings to text. Supports HTML and markdown by default.
Objective-C
23
star
15

DCSideNav

Custom Navigation for iPad. Similar to iPad twitter app navigation.
Objective-C
17
star
16

GPLib-iOS

General Purpose iOS library
Objective-C
10
star
17

DCDataViews

Simple and Powerful data management model for UITableView and UICollectionView to make simpler and faster to use.
Objective-C
10
star
18

FeedView

A simple feed based view in Swift with customizable and delightful animations. Think UICollectionView with the animations you always wanted.
Swift
9
star
19

DCSlideOutViewController

Does the slide view thing as seen in Path app.
Objective-C
7
star
20

DCAvatar

A simple, asynchronous, network based avatar library for iOS and OSX
Objective-C
6
star
21

SimpleSwiftApp

Just a basic Swift App using SwiftHTTP and JSONJoy
Swift
6
star
22

DCXMPP

XMPP library for iOS or OSX in objective-c
Objective-C
5
star
23

XMLKit-objc

XML parsing in objective-C
Objective-C
2
star
24

Sideswipe

Network Image Library in Swift
Swift
2
star
25

common-crypto-spm

common crypto headers provided for the Swift Package Manager
Swift
2
star
26

bazaarvoice-challenge

Bazaarvoice programming exercise
Swift
1
star
27

goguid

generate GUID and UUIDs in go.
Go
1
star
28

daltoniam.com

portfolio website
CSS
1
star