Swift
指令
hello.swift
#!/usr/bin/env swift
import Foundation
@_cdecl("sayHello")
public func sayHello() {
print("Hello from Swift!")
}
sayHello()
swift hello.swift
Start a server at port 8081
""
#!/usr/bin/env swift
import Foundation
import Network
// 设定监听的端口
let port = NWEndpoint.Port(rawValue: 8081)!
// 创建监听器
let listener = try! NWListener(using: .tcp, on: port)
// 新连接的处理函数
listener.newConnectionHandler = { connection in
connection.start(queue: .main) // 在主队列上启动连接
// 接收数据
connection.receive(minimumIncompleteLength: 1, maximumLength: 10000) {
(data, _, isComplete, error) in
if let data = data, !data.isEmpty {
let request = String(data: data, encoding: .utf8) ?? "Invalid request"
print("Received HTTP request:\n\(request)") // 打印接收到的请求
// HTTP 响应内容
let httpResponse = """
HTTP/1.1 200 OK\r
Content-Type: text/plain\r
Connection: close\r
\r
Hello, world from Swift server on port \(port)!
"""
// 发送响应
let responseData = httpResponse.data(using: .utf8)
connection.send(
content: responseData,
completion: .contentProcessed({ sendError in
if let error = sendError {
print("Failed to send response: \(error)")
}
connection.cancel() // 发送完毕后关闭连接
}))
} else if let error = error {
print("Failed to receive data: \(error)")
connection.cancel() // 出错时关闭连接
}
}
}
// 开始监听
listener.start(queue: .main)
print("Server started on port \(port)")
// 使主运行循环继续运行,防止程序退出
RunLoop.main.run()