-
Notifications
You must be signed in to change notification settings - Fork 149
Expand file tree
/
Copy pathConnect.swift
More file actions
72 lines (55 loc) · 2.06 KB
/
Copy pathConnect.swift
File metadata and controls
72 lines (55 loc) · 2.06 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
/*
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!"
@available(System 99, *)
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!")
}
}