The easy way to use sockets on Apple platforms

Overview

SwiftSocket

CocoaPods Compatible CocoaPods Platforms Carthage Compatible

SwiftSocket library provides as easy to use interface for socket based connections on server or client side. Supports both TCP and UDP sockets.

Installation

Cocoapods

Add this to your Podfile:

pod 'SwiftSocket'

And run then pod install

Carthage

github "swiftsocket/SwiftSocket"

Code examples

Create client socket

// Create a socket connect to www.apple.com and port at 80
let client = TCPClient(address: "www.apple.com", port: 80)

Connect with timeout

You can also set timeout to -1 or leave parameters empty (client.connect()) to turn off connection timeout.

 switch client.connect(timeout: 10) {
   case .success:
     // Connection successful 🎉
   case .failure(let error):
     // 💩
 }

Send data

let data: Data = // ... Bytes you want to send
let result = client.send(data: data)

Read data

var data = client.read(1024*10) //return optional [Int8]

Close socket

client.close()

Client socket example

let client = TCPClient(address: "www.apple.com", port: 80)
switch client.connect(timeout: 1) {
  case .success:
    switch client.send(string: "GET / HTTP/1.0\n\n" ) {
      case .success:
        guard let data = client.read(1024*10) else { return }

        if let response = String(bytes: data, encoding: .utf8) {
          print(response)
        }
      case .failure(let error):
        print(error)
    }
  case .failure(let error):
    print(error)
}

Server socket example (echo server)

func echoService(client: TCPClient) {
    print("Newclient from:\(client.address)[\(client.port)]")
    var d = client.read(1024*10)
    client.send(data: d!)
    client.close()
}

func testServer() {
    let server = TCPServer(address: "127.0.0.1", port: 8080)
    switch server.listen() {
      case .success:
        while true {
            if var client = server.accept() {
                echoService(client: client)
            } else {
                print("accept error")
            }
        }
      case .failure(let error):
        print(error)
    }
}
Comments
  • Is there any way to respond to incoming messages without polling?

    Is there any way to respond to incoming messages without polling?

    I am writing a client app and messages can appear from the server at any time. Is there a way of setting up a method that will be called when messages appear? I don't want to have to call read() repeatedly to see if there's anything received.

    Cool library, btw, I got everything else to work very easily.

    opened by fishtrousers 13
  • TCPClient.read() does not read everything

    TCPClient.read() does not read everything

    I use TCPClient.read() to read responses from a mpd server. The server itself sends more than, e.g. 2048 Bytes but I only receive 1448 Bytes:

    if let responseData = self.client.read(self.DATALEN) {
                print("Len: \(responseData.count)")
                response = String.init(bytes: responseData, encoding: String.Encoding.utf8)
    }
    
    opened by jpaffrath 9
  • Execution Order Error

    Execution Order Error

    Hi,

    I have developed a class derived from TCPClient to implement some write/read operations with a TCP server on a PLC. The actions I'm intended in perform are:

    1. Send a command (write) requisition and read requisition confirmation -> var(success,statusMessage,command) = Client.WriteCommand(CommandValue);
    2. Request some PLCs value(write) and read the values from PLC (read)-> var(success,statusMessage,data1,data2,data3) = Client.ReadData();

    When I execute each action in distinct button actions it works perfectly, but when I use them into one action at the sequence: var(success,statusMessage,command) = Client.WriteCommand(CommandValue); var(success,statusMessage,data1,data2,data3) = Client.ReadData();
    it seems the processes doesn't wait until the first line execution and try to execute the second one. It make mess in my protocol communication. Do you know if this lack of synchrony could be solved?

    Thanks

    opened by gupinheiro 8
  • UDPClient

    UDPClient

    Guys. Help please write such a program for UDP.

    class ViewController: UIViewController {
      
      @IBOutlet weak var textView: UITextView!
      
      let host = "apple.com"
      let port = 80
      var client: TCPClient?
    
      override func viewDidLoad() {
        super.viewDidLoad()
        
        client = TCPClient(address: host, port: Int32(port))
      }
      
      @IBAction func sendButtonAction() {
        guard let client = client else { return }
        
        switch client.connect(timeout: 10) {
        case .success:
          appendToTextField(string: "Connected to host \(client.address)")
          if let response = sendRequest(string: "GET / HTTP/1.0\n\n", using: client) {
            appendToTextField(string: "Response: \(response)")
          }
        case .failure(let error):
          appendToTextField(string: String(describing: error))
        }
      }
      
      private func sendRequest(string: String, using client: TCPClient) -> String? {
        appendToTextField(string: "Sending data ... ")
        
        switch client.send(string: string) {
        case .success:
          return readResponse(from: client)
        case .failure(let error):
          appendToTextField(string: String(describing: error))
          return nil
        }
      }
      
      private func readResponse(from client: TCPClient) -> String? {
        guard let response = client.read(1024*10) else { return nil }
        
        return String(bytes: response, encoding: .utf8)
      }
      
      private func appendToTextField(string: String) {
        print(string)
        textView.text = textView.text.appending("\n\(string)")
      }
    
    }
    
    opened by R2D6233 7
  • Help - developing an IoT app

    Help - developing an IoT app

    HI I'm trying to build some app on IoT using swift sockets. iPad will be client and it will send requisitions (for read tags and write commands) for industrial assets and I have some questions, could you help me?

    • I need to use delimiters in my messages or just fix size can guarantee messages could be read correctly?
    • Is it reasonable to polling read tags periodically and only write commands when necessary? In this approach how you suggest to do this operations and acess data read?
    • In case of fail? I just need to descart read and do another read? Thanks
    opened by gupinheiro 7
  • Not compatible with OS X?

    Not compatible with OS X?

    I'm trying to add SwiftSocket to my project (OS X app) using the Cocoapods, but pod install fails with an error:

    [!] The platform of the target my-app-name (OS X 10.11) is not compatible with SwiftSocket (1.2), which does not support osx.

    opened by DominikPalo 7
  • library not found for -lSwiftSocket

    library not found for -lSwiftSocket

    Using Xcode 11 and building against iOS 13, I'm getting the following error:

    ld: library not found for -lSwiftSocket clang: error: linker command failed with exit code 1 (use -v to see invocation)

    I made sure that I am opening the *.xcworkspace file, and I followed Cocoapod's troubleshooting steps.

    Any ideas what might be causing it? I did have to manually change the Pod's Swift version from 3 to 5.

    opened by arik-so 6
  • How to read all lines

    How to read all lines

    Hi, My problem is socket read only (1024*10) charaters. how to read all lines in swift 2 ?

    My code: private func sendRequest(data: String, client: TCPClient?) -> (String?) { // It use ufter connection if client != nil { // Send data (WE MUST ADD TO SENDING MESSAGE '\n' ) let (isSuccess, errorMessage) = client!.send(str: "(data)\n") if isSuccess { // Read response data let data = client!.read(1024*10) if let d = data { // Create String from response data if let str = NSString(bytes: d, length: d.count, encoding: NSUTF8StringEncoding) as? String { return (data: str) } else { return (data: nil) } } else { return (data: nil) } } else { print(errorMessage) return (data: nil) } } else { return (data: nil) } }

    and other question is here :http://stackoverflow.com/questions/34036070/how-to-read-all-lines-in-socket-swift

    opened by Clever91 4
  • I'm only seeing response header

    I'm only seeing response header

    Thank you for this, I apologize if this is obvious but I'm only seeing the response header and not the actual response from the server. I'm just using the posted example and printing the response into a UILabel. The response is plain text.

    I'm prototyping something and this library is very useful.

    UPDATE:

    Sorry I mistyped client.read(1024*10) I had some other number inside.

    UPDATE 2:

    it keeps happening, sometimes returns the headers only and not the data.

    opened by oncre 3
  • String.stringwithBytes() is not a type of String

    String.stringwithBytes() is not a type of String

    Do you know of a way to get around the string decoding that will work? I am seeing everything else just fine. Just the decoding on the read from my client server is not working.

    opened by clarkathon 3
  • Anybody has swiftSocket working as a Nativescript plugin?

    Anybody has swiftSocket working as a Nativescript plugin?

    I am not an IOS developer, but i need to be able to write to an ESCPOS printer. swift socket should be able to do this, however i could not yet get his to work as a nativescript plugin. My question: anybody already done this? I saw Aandrea Cremisini working on it, however no workable plugin is available under hit github account

    if it helps i can show you the plugin i got so far...

    Thanks for your help in advance...

    opened by growerp 2
  • Read Video file using TCPClient

    Read Video file using TCPClient

    Hi, I am using TCPClient send and received messages successfully but need to retrieve video file from TCPClient to mobile storage? I was try for let data1 = client.read(100,timeout: 5) it return nil. Please suggest sample reference. Thanks,

    opened by natheemy 0
  • Package.swift has no Package.swift manifest for version 2.1.0 in https://github.com/swiftsocket/SwiftSocket

    Package.swift has no Package.swift manifest for version 2.1.0 in https://github.com/swiftsocket/SwiftSocket

    Package.swift has error when I run the command:swift build 0.o PS E:\swift-projects\SocketLearn> swift run Updating https://github.com/swiftsocket/SwiftSocket Updated https://github.com/swiftsocket/SwiftSocket (1.21s) Computing version for https://github.com/swiftsocket/SwiftSocket error: /\Package.swift has no Package.swift manifest for version 2.1.0 in https://github.com/swiftsocket/SwiftSocket

    opened by Naonao9527 0
  • Add Swift Package Manager support

    Add Swift Package Manager support

    :pencil: Description

    • This PR adds Swift Package Manager support

    :bulb: What’s new?

    • SwiftSocket can be integrated via Swift Package Manager
    • iOS deployment target bumped to 9.0 in order to mitigate warning in newer Xcodes
    • Add instructions to README.md

    :no_mouth: What’s missing?

    • Add 2.2.0 tag after merge

    :books: References

    • https://stackoverflow.com/questions/49779543/swift-package-manager-c-interop-non-system-libraries
    opened by pchmelar 0
  • If using DNS name, how to get the IP Address after using TCPClient?

    If using DNS name, how to get the IP Address after using TCPClient?

    Greetings,

    I've tried looking in the code and on the net, can't figure out how to print or assign to a variable the IP Address resolved when using a DNS name, either is SwiftSocket or native SwiftUI function.

    What I do is something like: let client = TCPClient(address: www.google.com, port: 443). What I need then is to get the IP Address resolved for www.google.com from the device it's being run and for the life of me, cannot find anything to do that.

    All I find is how to get device's IP Address or the WiFi IP Address, but not the remote host I'm connecting to.

    I'm using XCode 13 and iOS 15.2.

    Thank you :)

    opened by mezzomix23 0
Releases(2.1.0)
Owner
null
Deal with query items, HTTP headers, request body and more in an easy, declarative way

Reusable system for complex URL requests with Swift. Deal with query items, HTTP headers, request body and more in an easy, declarative way. Check out our engineering blog to learn more!

Parable Health 19 Sep 5, 2022
Easy to use OAuth 2 library for iOS, written in Swift.

Heimdallr Heimdallr is an OAuth 2.0 client specifically designed for easy usage. It currently supports the resource owner password credentials grant f

trivago N.V. 628 Oct 17, 2022
Easy to use SMJobBless, along with a full Swift implementation of the Authorization Services and Service Management frameworks

Leverage SMJobBless functionality with just one function call: let message = "Example App needs your permission to do thingamajig." let icon = Bundle.

null 20 Dec 23, 2022
Easy to use CFNetwork wrapper for HTTP requests, Objective-C, Mac OS X and iPhone

ASIHTTPRequest is an easy to use wrapper around the CFNetwork API that makes some of the more tedious aspects of communicating with web servers easier

Ben Copsey 5.8k Dec 14, 2022
Easy-to-use ICMP Ping for iOS (and maybe OSX)

CDZPinger Easy-to-use ICMP ping for iOS - just create a CDZPinger and you delegate gets a callback every second with the average ping time. Installati

Chris Dzombak 48 Feb 2, 2022
The civilized way to write REST API clients for iOS / macOS

The elegant way to write iOS / macOS REST clients Drastically simplifies app code by providing a client-side cache of observable models for RESTful re

Bust Out 2.2k Nov 20, 2022
Music Room: a mobile app that offers a new way of experiencing music

?? Music Room - 42 School Project ?? ???? Music Room is a mobile app that offers

Marie-Lise Picard 3 Feb 18, 2022
EasyImplementationAlamoFire - An iOS project to demonstrate the usage of Alamofire in an efficient and organised way.

EasyImplementationAlamoFire Tutorial to demonstrate an efficient way of handling the APIs structure for your iOS Applications. Prerequisites Swift 5 X

null 0 Jan 3, 2022
Real-time Apps the SwiftUI way

Sync Sync is a proof of concept for expanding on the Magic of ObservableObject, and making it work over the network. This let's you create real-time A

Mathias Quintero 138 Dec 14, 2022
Replacement for Apple's Reachability re-written in Swift with closures

Reachability.swift Reachability.swift is a replacement for Apple's Reachability sample, re-written in Swift with closures. It is compatible with iOS (

Ashley Mills 7.7k Jan 1, 2023
Apple Push Notifications (APNs) Server-Side library.

Perfect-Notifications 简体中文 APNs remote Notifications for Perfect. This package adds push notification support to your server. Send notifications to iO

PerfectlySoft Inc. 113 Oct 28, 2022
macOS VM for Apple Silicon using Virtualization API

MacVM macOS Monterey added support for virtualizing macOS with Apple silicon host. This project provides an example project for the setup. Currently o

Khaos Tian 1.2k Jan 4, 2023
Google ProtocolBuffers for Apple Swift

Protocol Buffers for Swift An implementation of Protocol Buffers in Swift. Protocol Buffers are a way of encoding structured data in an efficient yet

Alexey Khokhlov 933 Nov 4, 2022
Updates to Apple's AVKitPlayerOSX sample code.

AVKitPlayerOSX =========================================================================== DESCRIPTION: This sample demonstrates usage of AVPlayerView

George Toledo 0 Nov 5, 2021
Simplified access to Apple's CloudKit

EVCloudKitDao Discuss EVCloudKitDao : What is this With Apple CloudKit, you can focus on your client-side app development and let iCloud eliminate the

Edwin Vermeer 632 Dec 29, 2022
Apple watch app to interface with Transmission Client

TransmissionWatch Apple watch app to interface with Transmission Client Currrent

Aayush 2 Dec 23, 2021
Login-screen-using-Swift - Firebase Apple Open Source Development

Firebase Apple Open Source Development This repository contains all Apple platfo

Kushal Shingote 1 Feb 3, 2022
NWReachability - a pure Swift library for monitoring the network connection of iOS devices using Apple's Network framework.

NWReachability is a pure Swift library for monitoring the network connection of iOS devices using Apple's Network framework.

null 4 Dec 2, 2022
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.

Zewo Graveyard 63 Jan 29, 2022