send a message to a tcp server in swift

To send a message to a TCP server in Swift, you can use the Socket class from the SwiftSocket library. Here is how you can do it:

main.swift
import SwiftSocket

// create a new socket and connect to the server
let socket = Socket.create() // create a new socket instance
let address = "127.0.0.1" // IP address of the server
let port = 12345 // port number of the server
try socket.connect(to: address, port: Int32(port))

// send a message to the server
let message = "Hello, server!"
try socket.write(from: message)

// close the socket
socket.close()
413 chars
15 lines

Here, we create a new socket instance, connect to the server using its IP address and port number, then send a message to the server using the write(from:) method. Finally, we close the socket using the close() method.

Note that this code code will throw an error if the connection or write operation fails, so you should wrap it in a do-catch block to handle any exceptions that may occur.

gistlibby LogSnag