SwiftSocket library provides 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
SwiftWebSocket - Conforming WebSocket (RFC 6455) client library for iOS and Mac OSX.

SwiftWebSocket Conforming WebSocket (RFC 6455) client library for iOS and Mac OSX. SwiftWebSocket passes all 521 of the Autobahn's fuzzing tests, incl

Josh Baker 1.5k Jan 5, 2023
The easy way to use sockets on Apple platforms

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

null 1.6k Dec 21, 2022
The easy way to use sockets on Apple platforms

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

null 1.6k Jan 3, 2023
Awesome-swift-platforms - A curated list of Swift on different platforms

Embedded Swift A curated list of Swift on different platforms. Nintendo Switch S

Devran Cosmo Uenal 4 Feb 6, 2022
Secure Sockets for Socks

[DEPRECATED] SecretSocks SSL/TLS addon for Socks. ⚠️ This project is now deprecated and will not receive any further maintenance. ?? Usage This packag

null 12 Feb 23, 2017
A simple library that provides standard Unicode emoji support across all platforms

Twitter Emoji (Twemoji) A simple library that provides standard Unicode emoji support across all platforms. Twemoji v13.1 adheres to the Unicode 13.0

Twitter 15k Jan 8, 2023
(Animate CSS) animations for iOS. An easy to use library of iOS animations. As easy to use as an easy thing.

wobbly See Wobbly in action (examples) Add a drop of honey ?? to your project wobbly has a bunch of cool, fun, and easy to use iOS animations for you

Sagaya Abdulhafeez 150 Dec 23, 2021
(Animate CSS) animations for iOS. An easy to use library of iOS animations. As easy to use as an easy thing.

wobbly See Wobbly in action (examples) Add a drop of honey ?? to your project wobbly has a bunch of cool, fun, and easy to use iOS animations for you

Sagaya Abdulhafeez 150 Dec 23, 2021
CITreeView created to implement and maintain that wanted TreeView structures for IOS platforms easy way

CITreeView CITreeView created to implement and maintain that wanted TreeView structures for IOS platforms easy way. CITreeView provides endless treevi

Cenk Işık 126 May 28, 2022
Easy to use cryptographic framework for data protection: secure messaging with forward secrecy and secure data storage. Has unified APIs across 14 platforms.

Themis provides strong, usable cryptography for busy people General purpose cryptographic library for storage and messaging for iOS (Swift, Obj-C), An

Cossack Labs 1.6k Dec 30, 2022
Easy to use cryptographic framework for data protection: secure messaging with forward secrecy and secure data storage. Has unified APIs across 14 platforms.

Themis provides strong, usable cryptography for busy people General purpose cryptographic library for storage and messaging for iOS (Swift, Obj-C), An

Cossack Labs 1.6k Dec 30, 2022
AZPeerToPeerConnectivity is a wrapper on top of Apple iOS Multipeer Connectivity framework. It provides an easier way to create and manage sessions. Easy to integrate

AZPeerToPeerConnection Controller Features Multipeer Connectivity Connection via Bluetooth or Wifi No need write all session, browser, services delega

Afroz Zaheer 66 Dec 19, 2022
Google Analytics tracker for Apple tvOS provides an easy integration of Google Analytics’ measurement protocol for Apple TV.

Google Analytics tracker for Apple tvOS by Adswerve About Google Analytics tracker for Apple tvOS provides an easy integration of Google Analytics’ me

Adswerve 81 Nov 13, 2022
IGStoryButtonKit provides an easy-to-use button with rich animation and multiple way inspired by instagram story/stories.

Introduction Have you ever seen UI like instagram story, haven't you? Actually, features like instagram story have been implemented in many applicatio

mutation 34 Nov 8, 2022
This library provides convenient way to use Coinpaprika.com API in Swift.

Coinpaprika API Swift Client Documentation | Repository | Installation Usage This library provides convenient way to use Coinpaprika.com API in Swift.

Coinpaprika 30 Dec 21, 2021
🚀 Create XCFrameworks with ease! A Command Line Tool to create XCFramework for multiple platforms at one shot! The better way to deal with XCFrameworks for iOS, Mac Catalyst, tvOS, macOS, and watchOS.

Surmagic ?? Create XCFramework with ease! A Command Line Tool to create XCFramework for multiple platforms at one shot! The better way to deal with XC

Muhammed Gurhan Yerlikaya 260 Dec 28, 2022
Imagine Engine - a fast, high performance Swift 2D game engine for Apple's platforms

Welcome to Imagine Engine, an ongoing project that aims to create a fast, high performance Swift 2D game engine for Apple's platforms that is also a j

John Sundell 1.8k Jan 3, 2023
A native Jellyfin client for Apple platforms (iOS, macOS and tvOS)

Jellyfin Swift (working title) is a native Swift app targeting all modern Apple devices (iOS, ipadOS, tvOS and macOS).

Julien Machiels 3 Jun 7, 2021
Home Assistant for Apple Platforms

Home Assistant for Apple Platforms Getting Started Home Assistant uses Bundler, Homebrew and Cocoapods to manage build dependencies. You'll need Xcode

null 0 Nov 23, 2021
Anime4K for Apple platforms based on Metal

Anime4KMetal Introduction This is a port of Anime4K to Metal. It dynamically translates GLSL shaders to Metal shaders and applies them during video pl

Yi Xie 18 Nov 22, 2022