Skip to content

WebSocket wrapper around URLSessionWebSocketTask used in our https://new.space/app iOS app

License

Notifications You must be signed in to change notification settings

shareup/websocket-apple

Folders and files

NameName
Last commit message
Last commit date

Latest commit

a176fc4 · Aug 15, 2024

History

28 Commits
Aug 15, 2024
Aug 15, 2024
Aug 15, 2024
Apr 10, 2023
Apr 10, 2023
Dec 4, 2023
Apr 10, 2023
Aug 15, 2024
Aug 15, 2024
Aug 15, 2024
Aug 15, 2024

Repository files navigation

WebSocket wrapper around URLSessionWebSocketTask

(macOS, iOS, iPadOS, tvOS, and watchOS)

A concrete implementation of a WebSocket client implemented by wrapping Apple's URLSessionWebSocketTask.

The public interface of WebSocket is a simple struct whose public methods are exposed as closures. The reason for this design is to make it easy to inject fake WebSockets into your code for testing purposes.

The actual implementation is SystemWebSocket, but this type is not publicly accessible. Instead, you can access it via WebSocket.system(url:) or WebSocket.system(request:). SystemWebSocket tries its best to mirror the documented behavior of web browsers' WebSocket. Please report any deviations as bugs.

WebSocket exposes a simple API and makes heavy use of Swift Concurrency.

Installation

To use WebSocket, add a dependency to your Package.swift file:

let package = Package(
  dependencies: [
    .package(
      url: "https://github.com/shareup/websocket-apple.git",
      from: "4.0.0"
    )
  ]
)

Usage

// `WebSocket` starts connecting to the specified `URL` immediately.
let socket = WebSocket.system(url: url(49999))

// Wait for `WebSocket` to be ready to send and receive messages.
try await socket.open()

// Send a message to the server
try await socket.send(.text("hello"))

// Receive messages from the server
for await message in socket.messages {
    print(message)
}

try await socket.close()

Tests

  1. In your Terminal, navigate to the websocket-apple directory
  2. Run the tests using swift test

Notices

This library includes code from WebSocketKit and SwiftNIO, the use of which depends on their licenses.