create a tcp server on a specific port in swift

To create a TCP server in Swift, you can use the Socket library. Here's an example of how to create a basic TCP server on a specific port:

main.swift
import Foundation
import Socket

let port = 12345 // Choose a port number

do {
    // Create a socket object
    let serverSocket = try Socket.create()
    
    // Bind the socket to the port number
    try serverSocket.listen(on: port)
    
    // Wait for a client to connect
    print("Waiting for connection on port \(port)")
    let clientSocket = try serverSocket.acceptClientConnection()
    print("Client connected!")
    
    // Do something with the client socket
    // For example, read data from the socket:
    let data = try clientSocket.read()
    print("Received data: \(data)")
    
    // Close the sockets
    clientSocket.close()
    serverSocket.close()
    
} catch let error {
    print("Error: \(error)")
}
733 chars
30 lines

This code creates a Socket object and binds it to the specified port number. It then waits for a client to connect and prints a message when a client connects. Once a client is connected, you can read data from the client socket using read().

Note that this TCP server example is blocking, meaning that it will wait until a client connects before executing any additional code.

gistlibby LogSnag