The easy way to use sockets on Apple platforms

Last update: Jun 21, 2022

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)
    }
}

GitHub

https://github.com/swiftsocket/SwiftSocket
Comments
  • 1. 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.

    Reviewed by fishtrousers at 2017-03-05 16:03
  • 2. 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)
    }
    
    Reviewed by jpaffrath at 2016-12-17 22:55
  • 3. 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

    Reviewed by gupinheiro at 2016-12-23 12:37
  • 4. 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)")
      }
    
    }
    
    Reviewed by R2D6233 at 2017-04-29 23:10
  • 5. 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
    Reviewed by gupinheiro at 2017-02-05 22:58
  • 6. 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.

    Reviewed by DominikPalo at 2016-12-28 10:42
  • 7. 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.

    Reviewed by arik-so at 2020-03-10 07:52
  • 8. 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

    Reviewed by Clever91 at 2015-12-07 11:12
  • 9. 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.

    Reviewed by oncre at 2015-03-01 01:58
  • 10. 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.

    Reviewed by clarkathon at 2015-01-14 22:25
  • 11. 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...

    Reviewed by growerp at 2020-02-10 13:16
  • 12. 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 :)

    Reviewed by mezzomix23 at 2022-03-11 20:35
  • 13. [!] Unknown command: `SwiftSocket`

    I typed : pod 'SwiftSocket' in Terminal, but return:

    [!] Unknown command: SwiftSocket Did you mean: list?

    Usage:

    $ pod COMMAND
    
      CocoaPods, the Cocoa library package manager.
    

    Commands:

    + cache         Manipulate the CocoaPods cache
    + deintegrate   Deintegrate CocoaPods from your project
    + env           Display pod environment
    + init          Generate a Podfile for the current directory
    + install       Install project dependencies according to versions from a
                    Podfile.lock
    + ipc           Inter-process communication
    + lib           Develop pods
    + list          List pods
    + outdated      Show outdated project dependencies
    + plugins       Show available CocoaPods plugins
    + repo          Manage spec-repositories
    + search        Search for pods
    + setup         Setup the CocoaPods environment
    + spec          Manage pod specs
    + trunk         Interact with the CocoaPods API (e.g. publishing new specs)
    + try           Try a Pod!
    + update        Update outdated project dependencies and create new Podfile.lock
    

    Options:

    --allow-root    Allows CocoaPods to run as root
    --silent        Show nothing
    --version       Show the version of the tool
    --verbose       Show more debugging information
    --no-ansi       Show output without ANSI codes
    --help          Show help banner of specified command
    

    How can I install SwiftSocket?

    Reviewed by Ferkelcode at 2022-02-02 05:11
  • 14. how can i read data in string formate

    Hi daer! How can i read data in string formate.... tell me any work around bacouse my server is sending back data in string formate... its urgent please please give me responce as soon as possible

    Reviewed by Fareeha-Naz at 2021-08-19 06:59
  • 15. From real device cannot able to send bytes

    Hi, i need to send array of bytes to server. I have tried from simulator I can able to send and getting response. to establish connection cam using client = TCPClient(address: myhost, port: myport) (in viewDidLoad) Same thing when I tried to send from iPhone device, connection is success but can not able to send bytes. I am getting following error.

    Error in data sent : "The operation couldn’t be completed. (SwiftSocket.SocketError error 3.)"

    am I need to do anything configuration in device?

    Reviewed by muga87 at 2021-07-22 13:38
Easy to use OAuth 2 library for iOS, written in Swift.
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

May 30, 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.

Jun 21, 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

Jun 17, 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

Feb 2, 2022
The civilized way to write REST API clients for iOS / macOS
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

Jun 26, 2022
Music Room: a mobile app that offers a new way of experiencing music
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

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

Jan 3, 2022
Real-time Apps the SwiftUI way
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

Jun 28, 2022
Replacement for Apple's Reachability re-written in Swift with closures
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 (

Jun 17, 2022
Apple Push Notifications (APNs) Server-Side library.
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

Apr 27, 2022
macOS VM for Apple Silicon using Virtualization API
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

Jun 26, 2022
Google ProtocolBuffers for Apple Swift
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

Jun 14, 2022
Updates to Apple's AVKitPlayerOSX sample code.

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

Nov 5, 2021
Simplified access to Apple's CloudKit
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

Apr 22, 2022
Apple watch app to interface with Transmission Client
Apple watch app to interface with Transmission Client

TransmissionWatch Apple watch app to interface with Transmission Client Currrent

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

Firebase Apple Open Source Development This repository contains all Apple platfo

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.

Mar 4, 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.

Jan 29, 2022
a NSURLCache subclass for handling all web requests that use NSURLRequest

EVURLCache What is this? This is a NSURLCache subclass for handeling all web requests that use NSURLRequest. (This includes UIWebView) The EVURLCache

Apr 18, 2022