2

I am newly to networks in iOS, I want to create tcp server/Client and I try many libraraies such as SwiftSocket, CocoaAsyncSocket, BlueSocket but I fail to reach my target, any one can provide me any example in swift to achieve my goal?

Ali A. Jalil
  • 873
  • 11
  • 25

1 Answers1

3

Your question is very broad. You can fill books with explaining TCP connections.

However, CocoaAsyncSocket is definitely your weapon of choice. You can use this framework to create any type of TCP or UDP connection, also with SSL. I can give you just two short examples, but you will have to read the documentation and also learn more about network connections in general. Especially, if you start using encrypted connections (which you should definitely do), it gets REALLY tricky. If you ask more specific questions, we can try to help you out.

Here is a short example for a TCP client connection:

import CocoaAsyncSocket

class TcpSocketConnection: GCDAsyncSocketDelegate {

    let tcpSocket: GCDAsyncSocket?

    init(host: String, port: UInt16) {
        self.tcpSocket = GCDAsyncSocket(delegate: self)
        do {
            try tcpSocket?.connect(toHost: host, onPort: port, withTimeout: 5.0)
        } catch let error {
            print("Cannot open socket to \(host):\(port): \(error)")
        }
    }

    // Needed by TcpSocketServer to start a connection with an accepted socket
    init(socket: GCDAsyncSocket, node: Node) {
        self.tcpSocket = socket
        self.tcpSocket?.delegate = self
    }

    func socket(_ sock: GCDAsyncSocket, didConnectToHost host: String, port: UInt16) {
        self.tcpSocket?.readData(toLength: 1024, withTimeout: 60.0)
    }

    func socket(_ sock: GCDAsyncSocket, didRead data: Data, withTag tag: Int) {
        // Process data
        self.tcpSocket?.readData(toLength: 1024, withTimeout: 60.0, tag: 0)
    }

    func send(_ data: Data) {
        //Send Data
        self.tcpSocket?.write(data, withTimeout: 10, tag: 0)
    }

}

And here is a short example for a TCP server:

import CocoaAsyncSocket

class TcpSocketServer: GCDAsyncSocketDelegate {

    let tcpSocket: GCDAsyncSocket?

    init(port: UInt16) {
        self.tcpSocket = GCDAsyncSocket(delegate: self)
        do {
            try self.socket.accept(onPort: port)
        } catch let error {
            print("Cannot listen on port \(self.port): \(error)")
        }
    }

    // Is called when a client connects to the server
    func socket(_ sock: GCDAsyncSocket, didAcceptNewSocket newSocket: GCDAsyncSocket) {
        // Creates new connection from server to client
        TcpSocketConnection(socket: newSocket)
    }

}

In this example, an active connection just reads in chunks of 1024 bytes and you need to trigger sending by yourself, but i hope you get the idea.

Nayan Dave
  • 1,078
  • 1
  • 8
  • 30
sundance
  • 2,930
  • 1
  • 20
  • 25