2024-10-03 05:03:39 +00:00
|
|
|
import Foundation
|
|
|
|
|
2024-10-03 05:22:10 +00:00
|
|
|
enum SocketState:String {
|
|
|
|
case connecting = "connecting"
|
|
|
|
case connected = "connected"
|
|
|
|
case disconnected = "disconnected"
|
|
|
|
}
|
|
|
|
|
|
|
|
@objc public class Sockets: NSObject, SocketDelegate {
|
|
|
|
|
|
|
|
private var sockets: [Socket] = []
|
|
|
|
|
|
|
|
private weak var plugin: SocketsPlugin?
|
|
|
|
@objc public init(plugin: SocketsPlugin? = nil) {
|
|
|
|
self.plugin = plugin
|
|
|
|
}
|
|
|
|
|
|
|
|
func didChangeState(socket: String, state: SocketState) {
|
|
|
|
self.plugin?.notifyListeners("state", data: [
|
|
|
|
"id": socket,
|
|
|
|
"state": state.rawValue
|
|
|
|
])
|
|
|
|
}
|
|
|
|
|
|
|
|
func didReceiveMessage(socket: String, message: String) {
|
|
|
|
self.plugin?.notifyListeners("message", data: [
|
|
|
|
"id": socket,
|
|
|
|
"message": message
|
|
|
|
])
|
|
|
|
}
|
|
|
|
|
2024-10-03 18:42:36 +00:00
|
|
|
@objc public func create(id: String) -> Socket {
|
|
|
|
let socket = Socket(id: id)
|
2024-10-03 05:22:10 +00:00
|
|
|
socket.delegate = self
|
|
|
|
sockets.append(socket)
|
|
|
|
return socket
|
|
|
|
}
|
|
|
|
|
2024-10-03 18:42:36 +00:00
|
|
|
@objc public func connect(id: String, host: String, port: Int, useTLS: Bool = false, acceptInvalidCertificates: Bool = false) {
|
2024-10-03 05:22:10 +00:00
|
|
|
if let socket = self.socket(with: id) {
|
2024-10-03 18:42:36 +00:00
|
|
|
socket.connect(host: host, port: port, useTLS: useTLS, acceptInvalidCertificates: acceptInvalidCertificates)
|
2024-10-03 05:22:10 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
@objc public func send(id: String, message: String) {
|
|
|
|
if let socket = self.socket(with: id) {
|
|
|
|
socket.write(message)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
@objc public func disconnect(id: String) {
|
|
|
|
if let socket = self.socket(with: id) {
|
|
|
|
socket.disconnect()
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
@objc func socket(with id: String) -> Socket? {
|
|
|
|
for socket in self.sockets {
|
|
|
|
if (socket.id == id) {
|
|
|
|
return socket
|
|
|
|
}
|
|
|
|
}
|
|
|
|
return nil
|
2024-10-03 05:03:39 +00:00
|
|
|
}
|
|
|
|
}
|