I m trying to connect to a Unix socket by using the library. But when i call my method from the AppDelegate Class it doesn't make a connection, i don't want to have multiple threads, it'll just be one single client connecting so, it should just make the connection write some data on the socket and block on a read call until the server writes back something and so on.
Below is the class, but as mentioned before when i call the .connectToDaemon()
function it doesn't actually connect. What am i doing wrong?
import Foundation
import Socket
class DaemonCommander {
var daemonSocket: Socket? = nil
var socketPath: String
static var bufferSize = 1024
init(sockPath: String) {
self.socketPath = sockPath
}
deinit {
self.daemonSocket?.close()
}
// connect sets up the socket and connects to the daemon sokcet
public func connectToDaemon() {
do {
print("Connect to daemon called")
// Create an unix socket...
try self.daemonSocket = Socket.create(family: .unix, type: .stream, proto: .unix)
guard let socket = self.daemonSocket else {
print("Unable to unwrap socket...")
return
}
self.daemonSocket = socket
try daemonSocket?.connect(to: self.socketPath)
} catch let error {
guard error is Socket.Error else {
print("Unexpected error...")
return
}
}
}
public func sendCommand(command: String) -> String {
let readData = Data(capacity: DaemonCommander.bufferSize)
do {
try self.daemonSocket?.write(from: command)
print(readData)
} catch let error {
guard error is Socket.Error else {
return "Unexpected error whilw connection"
}
}
return String(decoding: readData, as: UTF8.self)
}
}