Swiftpack.co - Package - Kitura/Kitura-WebSocket-Client

Kitura

Build Status - Master macOS Linux Apache 2 Slack Status

Kitura-WebSocket-Client

A WebSocket compression library based on SwiftNIO

WebSocket Client

WebSocket Client is a WebSocket endpoint, defined by RFC6455 allows to upgrade an existing HTTP connection to WebSocket connection and communicate.

This document discusses the implementation of WebSocket Client in Kitura-WebSocket-Client API using SwiftNIO.

This document assumes the reader is aware of the fundamentals of the WebSocket protocol.

Table of contents

Usage

Usage

Add dependencies

Add the Kitura-WebSocket-Client package to the dependencies within your application’s Package.swift file. Substitute "x.x.x" with the latest Kitura-WebSocket-Client release.

.package(url: "https://github.com/Kitura/Kitura-WebSocket-Client.git", from: "x.x.x")

Add Kitura-WebSocket-Client to your target's dependencies:

.target(name: "example", dependencies: ["KituraWebSocketClient"]),

Import package

import KituraWebSocketClient

Creating a new WebSocket Client

Add a WebSocket Client to your application as follows:

let client = WebSocketClient(host: "localhost", port: 8989, uri: "/", requestKey: "test")

or

let client = WebSocketClient("ws://localhost:8080")

To enable compression the structure WebSocketCompressionConfiguration needs to be passed as an argument.

For example :

let client = WebSocketClient(host: "localhost", port: 8989, uri: "/", requestKey: "test", compressionConfig: WebSocketCompressionConfiguration())

Sending WebSocket Messages

Using this library makes sending messages, be it binary or text easier. For example code for sending a text message to WebSocket server:

client.sendMessage("Kitura-WebSocket")

Similarly the apis sendBinary, ping, pong,close sends binary data, ping, pong and close frames to server respectively.

Recieving Messages

Messages can be recieved on client either by creating WebSocketClientDelegate or competion call backs. Delegates are prioritized over completion call backs in this library.

To recieve a simple text message from client, we have :

client.onMessage { recievedText in  // receieved String
                    // do something with recieved String
               }

Similarly we have apis to recieve binary data(client.onBinary{}), ping(client.onPing{}), etc.

note: Usage of delegates to recieve message can be found here.