create a tcp client on a specific port in swift

To create a TCP client on a specific port in Swift, you can use Apple's Network framework. Here is an example code snippet that creates a TCP client on port 8080:

main.swift
import Network

// create a TCP client endpoint
let endpoint = NWEndpoint.hostPort(host: NWEndpoint.Host("localhost"), port: NWEndpoint.Port(rawValue: 8080)!)

// create a TCP connection
let tcpConnection = NWConnection(to: endpoint, using: .tcp)

// start the connection
tcpConnection.start(queue: .global()) { error in
    if let error = error {
        print("Error connecting: \(error)")
        return
    }
    print("Connected!")
    
    // send data across the connection
    let dataToSend = "Hello, server!".data(using: .utf8)!
    tcpConnection.send(content: dataToSend, completion: .contentProcessed({ error in
        if let error = error {
            print("Error sending data: \(error)")
            return
        }
        print("Data sent!")
    }))
    
    // receive data from the connection
    tcpConnection.receive(minimumIncompleteLength: 1, maximumLength: 65536) { (data, _, isComplete, error) in
        if let error = error {
            print("Error receiving data: \(error)")
            return
        }
        // handle the received data
        if let data = data, !data.isEmpty {
            print("Received data: \(String(data: data, encoding: .utf8)!)")
        }
        
        // close the connection
        tcpConnection.cancel()
    }
}
1283 chars
42 lines

In this code snippet, we first create a NWEndpoint with the host and port we want to connect to. Then, we create a NWConnection with the endpoint and specify that we want to use the TCP protocol. We start the connection and handle any errors that occur. Once the connection is established, we can send data across the connection using tcpConnection.send() and receive data using tcpConnection.receive(). Finally, we cancel the connection when we are done with it.

gistlibby LogSnag