让你的 Swift 应用程序通过 TCP、UDP 或 Unix 套接字与其他程序通信。
检查系统上 sshd 是否正在运行
import UniSocket
do {
let socket = try UniSocket(type: .tcp, peer: "localhost", port: 22)
try socket.attach()
let data = try socket.recv()
let string = String(data: data, encoding: .utf8)
print("server responded with:")
print(string)
try socket.close()
} catch UniSocketError.error(let detail) {
print(detail)
}
发送 HTTP 请求并等待最小所需大小的响应
import UniSocket
do {
let socket = try UniSocket(type: .tcp, peer: "2a02:598:2::1053", port: 80)
try socket.attach()
let request = "HEAD / HTTP/1.0\r\n\r\n"
let dataOut = request.data(using: .utf8)
try socket.send(dataOut!)
let dataIn = try socket.recv(min: 16)
let string = String(data: dataIn, encoding: .utf8)
print("server responded with:")
print(string)
try socket.close()
} catch UniSocketError.error(let detail) {
print(detail)
}
使用自定义超时值通过 UDP 查询 DNS 服务器
import UniSocket
import DNS // https://github.com/Bouke/DNS
do {
let timeout: UniSocketTimeout = (connect: 2, read: 2, write: 1)
let socket = try UniSocket(type: .udp, peer: "8.8.8.8", port: 53, timeout: timeout)
try socket.attach() // NOTE: due to .udp, the call doesn't make a connection, just prepares socket and resolves hostname
let request = Message(type: .query, recursionDesired: true, questions: [Question(name: "www.apple.com.", type: .host)])
let requestData = try request.serialize()
try socket.send(requestData)
let responseData = try socket.recv()
let response = try Message.init(deserialize: responseData)
print("server responded with:")
print(response)
try socket.close()
} catch UniSocketError.error(let detail) {
print(detail)
}
检查本地 MySQL 服务器是否正在运行
import UniSocket
do {
let socket = try UniSocket(type: .local, peer: "/tmp/mysql.sock")
try socket.attach()
let data = try socket.recv()
print("server responded with:")
print("\(data.map { String(format: "%c", $0) }.joined())")
try socket.close()
} catch UniSocketError.error(let detail) {
print(detail)
}
由 Daniel Fojt 编写,版权归 Seznam.cz 所有,根据 Apache License 2.0 条款获得许可。