send a binary message to a tcp server in swift

To send a binary message to a TCP server in Swift, you can use the Socket class from the Foundation framework. Here's an example of how to do it:

main.swift
import Foundation

// Create a TCP socket
guard let socket = try? Socket.create(family: .inet, type: .stream, proto: .tcp) else {
    print("Could not create socket")
    return
}

// Connect to the server
let address = "localhost"
let port = 1234

do {
    try socket.connect(to: address, port: Int32(port), timeout: 10)
} catch {
    print("Could not connect to server: \(error)")
    return
}

// Prepare the binary data you want to send
let data = Data(bytes: [0x01, 0x02, 0x03, 0x04, 0x05])

// Send the data to the server
let bytesWritten = try? socket.write(from: data)
print("Sent \(bytesWritten ?? 0) bytes to the server")

// Clean up the socket
socket.close()
671 chars
29 lines

In this example, we create a TCP socket and connect to a server running on localhost at port 1234. We then prepare some binary data using the Data class and write it to the socket using the write(from:) method. Finally, we close the socket.

Note that this is just a simple example and you'll probably want to add error handling and other features if you're building a real client/server application.

gistlibby LogSnag