这是使用Singleton在Swift 3中管理套接字连接的正确方法吗?
我在哪里开始套接字连接,以至于我不必每次都在Viewcontroller生命周期中重新连接? Viewcontroller不断向我的服务器发送数据;我的应用程序是客户端及其收集数据;它从应用程序中移动数据并发送方向,电源等。
我搜索过,但找不到具体的例子;我只找到套接字库,但没有任何关于如何在UIViewcontroller中使用它的示例;此外,大多数在线示例都使用websockets,我不是
有什么建议吗?
我希望这会奏效:
manager.messageReceived(message: "Testing...")
但我担心的是,在UIViewcontroller类中,它会自动重新启动连接;另外,我不确定我应该检查连接是否丢失以及再次连接的位置;因为我永远不会关闭套接字
谢谢
Singleton类:
import Darwin
import Foundation
class ChatManager {
// Add property for socket
private var control_socket: Int32
private var address = "000.000.0.000"
private var port = "0000"
class var sharedInstance: ChatManager {
struct Singleton { static let instance = ChatManager() }
return Singleton.instance
}
init() {
// Create the socket
self.control_socket = connectToServer(atAddress: self.address, atPort: self.port)
}
func sendMessage(message: String) {
// Push the message onto the socket
_ = write(self.control_socket, message, message.characters.count)
}
// Delegate methods
func messageReceived(message: String) {
// Emit the message using NSNotificationCenter
}
}
的UIViewController:
import Darwin
import Foundation
import UIKit
import Dispatch
class ViewController: UIViewController {
@IBOutlet private weak var joystickMove: Joystick!
@IBOutlet private weak var joystickRotate: Joystick!
private var contour = Contours()
private var contour_index: Int = 0
private let manager = ChatManager.sharedInstance
override func viewDidLoad() {
super.viewDidLoad()
createJoystick()
createContours()
createButton()
}
private func createJoystick() {
var joystick = Joystick()
let n: CGFloat = 100.0
let x: CGFloat = (UIScreen.main.bounds.width/2) - (n/2.0)
let y: CGFloat = UIScreen.main.bounds.height - (UIScreen.main.bounds.height/4.0)
joystick.frame = CGRect(x: x, y: y, width: n, height: n)
joystick.backgroundColor = UIColor.clear
joystick.substrateColor = UIColor.lightGray
joystick.substrateBorderColor = UIColor.gray
joystick.substrateBorderWidth = 1.0
joystick.stickSize = CGSize(width: 50.0, height: 50.0)
joystick.stickColor = UIColor.darkGray
joystick.stickBorderColor = UIColor.black
joystick.stickBorderWidth = 2.0
joystick.fade = 0.5
var packet = ""
joystick.trackingHandler = { (data) -> () in
let power = sqrt(pow(Double(data.velocity.x), 2.0) + pow(Double(data.velocity.y), 2.0))
let theta = atan2(Double(-data.velocity.y), Double(data.velocity.x))
let degrees = theta * (180.0 / M_PI)
if degrees >= 55 && degrees <= 125 { // move forward
packet = "\(1) \(1) \(power) \(power)"
} else if degrees >= -125 && degrees <= -55 { // move backewards
packet = "\(-1) \(-1) \(power) \(power)"
} else if degrees >= -55 && degrees <= 55 { // turn right
packet = "\(1) \(-1) \(power) \(power)"
} else if (degrees >= 125 && degrees <= 180) && (degrees >= -180 && degrees <= -125) { // turn left
packet = "\(-1) \(1) \(power) \(power)"
}
}
manager.messageReceived(message: "Testing...")
view.addSubview(joystick)
}
}
答案 0 :(得分:0)
由于它是单例,您是否考虑过在AppDelegate的应用程序功能中初始化套接字管理器?然后它将在应用程序的生命周期中存在。