A swift client for interacting with NATS servers

Overview

SwiftyNats

A maintained swift client for interacting with a nats server based on NIO2.

SwiftyNats Logo

Tested with Swift 5.4 on macos and Linux

Swift Version Compatibility:

Platform Compatibility:

Support

Join the #swift channel on nats.io Slack. We'll do our best to help quickly. You can also just drop by and say hello. We're looking forward to developing the community.

Installation via Swift Package Manager

In Package.swift

Add this packages as a dependency in your projects Package.swift file and add the Name to your target like shown in this example:

// swift-tools-version:5.4

import PackageDescription

let package = Package(
    name: "YourApp",
    products: [
        .executable(name: "YourApp", targets: ["YourApp"]),
    ],
    dependencies: [
        .package(name: "SwiftyNats", url: "https://github.com/aus-der-technik/SwiftyNats.git", from: "2.2.0")
    ],
    targets: [
        .target(
            name: "YourApp",
            dependencies: ["SwiftyNats"]
        ),
    ]
)

In an .xcodeproj

Open the project inspector in XCode and select your project. It is importent to select the project and not a target! Klick on the third tab Package Dependencies and add the git url https://github.com/aus-der-technik/SwiftyNats.git by selecting the litte +-sign at the end of the package list.

Basic Usage

import SwiftyNats

// register a new client
let client = NatsClient("http://nats.server:4222")

// listen to an event
client.on(.connect) { _ in
    print("Client connected")
}

// try to connect to the server 
try? client.connect()

// subscribe to a channel with a inline message handler. 
client.subscribe("foo.bar") { message in
    print("payload: \(message.payload)")
    print("size: \(message.byteCount)")
    print("reply subject: \(message.replySubject.subject)")
}

// publish an event onto the message strem into a subject
client.publish("this event happened", to: "foo.bar")

Setting the loglevel

The default loglevel is .error. You can reset it to see more verbose messages. Possible Values are .debug, .info, .error or .critical

let client = NatsClient("http://nats.server:4222")
client.config.loglevel = .info

Reconnection is up to you

Reconnection is not part of this package, because if a server diconnects your application have to be sure that subscribtions are made up again correctly.

With SwiftyNats this is a very easy step:

// register a new client
let client = NatsClient(url)

// listen to the .disconnected event to try a reconnect 
client.on(.disconnected) { [self] _ in
    sleep(5);
    try? client.reconnect()
    doSubscribe()
}

// subscribe to the channels
doSubscribe()

// private function to subscribe to channels
private func doSubscribe(){
    client.subscribe("foo.bar") { message in
        print("payload: \(message.payload)")
    }
}

List of events

The public class NatsEvent contains all events you can subscribt to.

event description
connected The client is conected to the server.
disconnected The client disconnects and was connectd before.
response The client gets an response from the server (internal).
error The server sends an error that can't be handled.
dropped The clients droped a message. Mostly because of queue length to short.
reconnecting The client reconencts to the server, (Because of a called reconnect()).
informed The server sends his information data successfully to the client.

Information about the connected server

Since 2.0.2 it is possible to get the informations from the conencted server

let client = NatsClient("http://nats.server:4222")
print("\(client.serverInformation.serverName) has Version: \(client.serverInformation.version))");

Contribution

Contribution is always welcome. Just send me a pull request.

Changelog

2.2.0

  • The client configuration is now publicly available
  • The handling of the connection status has been rewritten
  • Rewrite of the connection setup
  • The connection termination was rewritten
  • All classes have been cleaned up (refactoring)
  • A new license was added (BSD-0)
  • The reconnection code was removed
  • Subscription queue is an optional property of NatsSubject

2.1.1

  • rewrite the ChannelHandler: remove a bug that could lead into dropped messages.

2.1.0

  • uses NIO2
  • works with Vapor, now!

2.0.3

  • supports iOS anf tvOS

2.0.2

  • Get information from the connected Server (Version, name, id, ...)

2.0.1

  • Test with GitHub Actions
  • Update Dockerfile to build and test on Swift 5.4 (Linux)
  • Test with a real NATS-Server on macos
  • Cleanup unused definitions
  • Update Informations, do project care

2.0.0

  • Tested with NATS 2.3.4
  • Introduced logging
  • Updated depricated functions

Roadmap

See: Contribution ;)

  • Propper function description is needed
You might also like...
HTTPClient - HTTP Client With Swift

HTTPClient Ex. Search Repository import HTTPClient let url: URL = .init(string:

Open source Reddit client for iOS built entirely in Swift
Open source Reddit client for iOS built entirely in Swift

Area51 Area51 is an open source Reddit client for iOS built entirely in Swift! Get the public beta on TestFlight Join the public Slack channel to coll

🔌  Non-blocking TCP socket layer, with event-driven server and client.
🔌 Non-blocking TCP socket layer, with event-driven server and client.

Original authors Honza Dvorsky - http://honzadvorsky.com, @czechboy0 Matthias Kreileder - @matthiaskr1 At the request of the original authors, we ask

Restofire is a protocol oriented networking client for Alamofire
Restofire is a protocol oriented networking client for Alamofire

Restofire is a protocol oriented networking client for Alamofire. Features Requirements Installation Usage License Features Global Configuration for h

Socket.io iOS and OSX Client compatible with v1.0 and later
Socket.io iOS and OSX Client compatible with v1.0 and later

SocketIO-Kit ⚠️ This project is no longer maintained. Please use the official framework Socket.IO-Client-Swift. SocketIO-Kit is a Socket.io iOS client

WebSocket implementation for use by Client and Server

WebSocket ⚠️ This module contains no networking. To create a WebSocket Server, see WebSocketServer. To create a WebSocket Client, see WebSocketClient.

Stacksift Frontend Client
Stacksift Frontend Client

Stacksift Client App A Stacksift client for macOS. This is quick-and-dirty Stacksift client. It provides minimal filtering of reports, along with a wa

 Postie - The Next-Level HTTP API Client using Combine
Postie - The Next-Level HTTP API Client using Combine

Postie - The Next-Level HTTP API Client using Combine Postie is a pure Swift library for building URLRequests using property wrappers.

A conforming Objective-C WebSocket client library.

SocketRocket A conforming WebSocket (RFC 6455) client library for iOS, macOS and tvOS. Test results for SocketRocket here. You can compare to what mod

Comments
  • Release/2.2.0

    Release/2.2.0

    Ready to release 2.2.0

    • The client configuration is now publicly available
    • The handling of the connection status has been rewritten
    • Rewrite of the connection setup
    • The connection termination was rewritten
    • All classes have been cleaned up (refactoring)
    • A new license was added (BSD-0)
    • The reconnection code was removed
    • Subscription queue is an optional property of NatsSubject
    opened by petershaw 0
Releases(2.2.0)
  • 2.2.0(Oct 22, 2021)

    • The client configuration is now publicly accessible
    • The handling of the connection status has been rewritten and improved
    • The connection setup has been rewritten and improved
    • The connection termination has been rewritten and improved
    • All classes were cleaned up (refactoring)
    • A new license was added (BSD-0)
    • The reconnection code was removed, it is now up to the implementation code - could have been never worked in the original codebase.
    • Provide a reconnect() function to handling reconnect easily. (example given)
    • The subscription queue is an optional property of NatsSubject now
    Source code(tar.gz)
    Source code(zip)
  • 2.1.1(Oct 12, 2021)

    Removed a bug that could lead into dropped messages.

    • Complete rewrite of the ChannelHandler
    • Correct handling of incomming bytes
    • In addition, the redesign of the component brings a huge performance gain.

    Support via nats.io Slack Channel: https://natsio.slack.com/archives/C02D41BU0PQ

    Source code(tar.gz)
    Source code(zip)
Owner
aus der Technik - Simon & Simon GbR
aus der Technik - Simon & Simon GbR
A lightweight library for writing HTTP web servers with Swift

Taylor Disclaimer: Not actively working on it anymore. You can check out some alternatives Swift 2.0 required. Working with Xcode 7.1. Disclaimer: It

Jorge Izquierdo 925 Nov 17, 2022
Twitter-Client - A twitter client that allow users to view tweets on their iphone

Project 3 - Twitter Client Name of your app is a basic twitter app to read your

null 0 Feb 7, 2022
MQTTNIO - Non-blocking, event-driven Swift client for MQTT build on SwiftNIO

This library has support for WebSocket connections and TLS. It runs on all platforms Swift NIO runs on (e.g. macOS, iOS, Linux, etc.).

Steven Roebert 41 Dec 23, 2022
A barebones Swift HTTP client with automatic JSON response parsing.

HTTP Client A barebones Swift HTTP client with automatic JSON response parsing. Installation Add HTTP Client as a dependency through Xcode or directly

Joe Masilotti 30 Oct 11, 2022
A simple GCD based HTTP client and server, written in 'pure' Swift

SwiftyHTTP Note: I'm probably not going to update this any further - If you need a Swift networking toolset for the server side, consider: Macro.swift

Always Right Institute 116 Aug 6, 2022
📱  A strongly-typed, caching GraphQL client for iOS, written in Swift.

Apollo iOS is a strongly-typed, caching GraphQL client, written in Swift. It allows you to execute queries and mutations against a GraphQL server, and

Apollo GraphQL 3.6k Jan 7, 2023
An unofficial supported Swift client library for accessing News API.

An unofficial supported Swift client library for accessing News API.

Fumiya Yamanaka 9 Oct 1, 2022
Language Server Protocol (LSP) client for Swift

LanguageClient This is a Swift library for abstracting and interacting with language servers that implement the Language Server Protocol. It is built

Chime 35 Jan 1, 2023
A web API client in Swift built using Async/Await

Get A modern web API client in Swift built using Async/Await and Actors. let cli

Alexander Grebenyuk 745 Jan 3, 2023
SoundCloud client written on Swift

SoundCloud client written on Swift to integrate it easily with your apps. Features Fluent interface based on Models Reactive API with ReactiveCocoa 4.

Pedro Piñera Buendía 564 Mar 24, 2022