/// ================= 客户端运行程序 =================
/// 创建 socket 接口
var sockfd_client:Int32
/// 用于bind服务端信息的 protofamily AN_INIT 决定ipv4(32位IP地址)和端口号(16位)的组合
var server_addr:sockaddr_in
// 第一步:应对服务器的 socket 参数分别是:协议域(族) socket类型 协议
sockfd_client = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP)
// 第二步:填充服务器socket的信息
server_addr = sockaddr_in()
server_addr.sin_family = sa_family_t(AF_INET)
// let _ = "127.0.0.1".data(using: .ascii)?.withUnsafeBytes({
// (ptr: UnsafePointer<Int8>) in
// inet_pton(AF_INET, ptr, &server_addr.sin_addr.s_addr)
// })
server_addr.sin_addr.s_addr = inet_addr("127.0.0.1")
server_addr.sin_port = CFSwapInt16(6969)
// 第三步:连接服务器 自动分配一个端口
//一种方式通过withUnsafePointer withMemoryRebound
// let _ = withUnsafePointer(to: &server_addr){
// ptr in
// ptr.withMemoryRebound(to: sockaddr.self, capacity: 1) {
// ptrSockAddr in
// connect(sockfd_client, UnsafePointer(ptrSockAddr), socklen_t(MemoryLayout<sockaddr>.size))
// }
// }
//一种方式通过memcpy
var sock_addr = Darwin.sockaddr(sa_len: 0, sa_family: 0, sa_data: (0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0))
memcpy(&sock_addr, &server_addr, Int(MemoryLayout.size(ofValue: server_addr)))
connect(sockfd_client, &sock_addr, socklen_t(MemoryLayout<sockaddr>.size))
var message = "12345678"
let _ = message.data(using: .ascii)?.withUnsafeBytes({ (ptr:UnsafePointer<Int8>)in
// 第四步: 向服务器发送一条信息
send(sockfd_client, ptr, message.characters.count, 0)
})
close(sockfd_client)
网友评论