mirror of
https://github.com/apple/swift-system
synced 2026-11-23 04:34:26 +00:00
Add socket APIs to swift-system (#281) Port the long-standing sockets implementation from #30 to the new staging branch. This adds comprehensive low-level Swift APIs for POSIX socket programming. Original Co-authored-by: Karoy Lorentey <karoly@apple.com>
72 lines
2.0 KiB
Swift
72 lines
2.0 KiB
Swift
/*
|
|
This source file is part of the Swift System open source project
|
|
|
|
Copyright (c) 2021 - 2025 Apple Inc. and the Swift System project authors
|
|
Licensed under Apache License v2.0 with Runtime Library Exception
|
|
|
|
See https://swift.org/LICENSE.txt for license information
|
|
*/
|
|
|
|
import ArgumentParser
|
|
import SystemSockets
|
|
|
|
struct Connect: ParsableCommand {
|
|
static let configuration = CommandConfiguration(
|
|
abstract: "Connect to a TCP server and send/receive messages"
|
|
)
|
|
|
|
@Argument(help: "The host to connect to")
|
|
var host: String
|
|
|
|
@Argument(help: "The port to connect to")
|
|
var port: UInt16
|
|
|
|
@Option(name: .shortAndLong, help: "Message to send")
|
|
var message: String = "Hello from swift-system sockets!"
|
|
|
|
func run() throws {
|
|
print("Resolving \(host)...")
|
|
|
|
// Resolve the hostname
|
|
let hints = SocketAddress.ResolutionHints(family: .ipv4, socketType: .stream, protocol: .tcp)
|
|
let addresses = try SocketAddress.resolve(hostname: host, service: "\(port)", hints: hints)
|
|
|
|
guard let first = addresses.first else {
|
|
print("No addresses found for \(host)")
|
|
return
|
|
}
|
|
|
|
print("Connecting to \(first.address.ipv4?.description ?? "unknown")...")
|
|
|
|
// Create socket
|
|
let socket = try SocketDescriptor.open(first.family, first.socketType, protocol: first.protocol)
|
|
defer { try? socket.close() }
|
|
|
|
// Connect
|
|
try socket.connect(to: first.address)
|
|
print("Connected!")
|
|
|
|
// Send message
|
|
let messageBytes = Array(message.utf8)
|
|
let sent = try messageBytes.withUnsafeBytes { buffer in
|
|
try socket.send(UnsafeRawBufferPointer(buffer))
|
|
}
|
|
print("Sent \(sent) bytes: \(message)")
|
|
|
|
// Receive response
|
|
var buffer = [UInt8](repeating: 0, count: 4096)
|
|
let received = try buffer.withUnsafeMutableBytes { buffer in
|
|
try socket.receive(into: buffer)
|
|
}
|
|
|
|
if received > 0 {
|
|
let response = String(decoding: buffer.prefix(received), as: UTF8.self)
|
|
print("Received \(received) bytes: \(response)")
|
|
} else {
|
|
print("Connection closed by server")
|
|
}
|
|
|
|
print("Done!")
|
|
}
|
|
}
|