[BREAKGLASS] Append-only mirror of github.com/bluewallet/SwiftSocket
Go to file
2017-01-06 17:55:04 +03:00
iOS Example Add iOS example 2016-11-16 15:56:34 +03:00
Sources Move servers and clients to separate fies 2017-01-06 17:55:04 +03:00
SwiftSocket.xcodeproj Move servers and clients to separate fies 2017-01-06 17:55:04 +03:00
.gitignore Update gitignore 2016-11-05 13:17:48 +03:00
.swift-version Merge pull request #2 from danshevluk/development 2016-11-05 12:46:49 +03:00
LICENSE Create LICENSE 2016-11-30 11:11:05 +03:00
README.md Update README.md 2017-01-04 10:00:12 +08:00
SwiftSocket.podspec Release 2.0.1 2016-12-18 14:39:23 +03:00

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:\(c.address)[\(c.port)]")
    var d = c.read(1024*10)
    c.send(data: d!)
    c.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)
    }
}