Hi, I try to create a socket client to connect to a server, and get/send data as well. My code as below, it connected successfully to the server, but I don't how to receive /send data. Can somebody help me out of this?
import Foundation
import CoreFoundation
class SocketClient {
private(set) var host: String
private(set) var port: Int
private var socket: CFSocket?
init(_ host:String, _ port: Int){
self.host = host
self.port = port
}
func connect(){
//create socket
self.socket = CFSocketCreate(kCFAllocatorDefault, PF_INET, SOCK_STREAM, IPPROTO_TCP, CFSocketCallBackType.dataCallBack.rawValue, {
socket, callBackType, address, data, info in
if CFSocketCallBackType.dataCallBack == callBackType && data != nil {
debugPrint("incomming。。。")
}
}, nil)
guard self.socket != nil else{
debugPrint("create socket failed")
return
}
//binding ip
var address: sockaddr_in = sockaddr_in()
address.sin_family = sa_family_t(PF_INET)
address.sin_port = in_port_t(self.port)
var inAddr = in_addr()
inAddr.s_addr = inet_addr(self.host)
address.sin_addr = inAddr
let addrData = CFDataCreate(kCFAllocatorDefault, &address, MemoryLayout.size(ofValue: address))
let result = CFSocketConnectToAddress(self.socket, addrData, 5)
if result == .success {
debugPrint("connect succeed")
} else {
debugPrint("connect failed")
}
let source = CFSocketCreateRunLoopSource(kCFAllocatorDefault, self.socket, 1)
CFRunLoopAddSource(CFRunLoopGetCurrent(), source, .commonModes)
}
}