create a tcp client in swift

To create a TCP client in Swift, you can make use of the Socket class from the Foundation framework. Here's a basic example:

main.swift
import Foundation
import Network

class TCPClient {
    
    private let host: NWEndpoint.Host
    private let port: NWEndpoint.Port
    private var connection: NWConnection?
    
    init(host: String, port: Int) {
        self.host = NWEndpoint.Host(host)
        self.port = NWEndpoint.Port(rawValue: UInt16(port))!
    }
    
    func send(message: String, completion: @escaping (Result<Void, Error>) -> Void) {
        let data = message.data(using: .utf8)!
        connect()
        connection?.send(content: data, completion: .contentProcessed({ error in
            if let error = error {
                completion(.failure(error))
            } else {
                completion(.success(()))
            }
            disconnect()
        }))
    }
    
    private func connect() {
        connection = NWConnection(host: host, port: port, using: .tcp)
        connection?.start(queue: .main)
    }
    
    private func disconnect() {
        connection?.cancel()
    }
    
}
990 chars
38 lines

In this example, we define a class TCPClient that represents a socket-based TCP client. We store the host and port that we want to connect to in properties of the class. These are used to create an NWEndpoint object when we connect to the server.

We define a send method that takes a message as a String parameter and a completion handler that is called once the message has been sent. The message is converted to a Data object using UTF-8 encoding and then sent using the connection?.send method. Once the message has been sent, the completion handler is called with a success or failure result, and the connection is disconnected.

The connect method creates a new NWConnection object and starts the connection on the main queue. The disconnect method cancels the connection.

You can use this client by creating a new instance of the TCPClient class and calling the send method with your message and a completion handler. For example:

main.swift
let client = TCPClient(host: "localhost", port: 5000)
client.send(message: "Hello, world!") { result in
    switch result {
    case .success:
        print("Message sent successfully!")
    case .failure(let error):
        print("Error sending message: \(error.localizedDescription)")
    }
}
295 chars
10 lines

gistlibby LogSnag