//
|
// SocketManager.swift
|
// WanPai
|
//
|
// Created by 无故事王国 on 2023/10/31.
|
//
|
|
import Foundation
|
import RHSocketKit
|
import RxSwift
|
import RxCocoa
|
import HandyJSON
|
|
/// Sockt管理类
|
class YYSocketManager: NSObject {
|
|
//仿OC写法
|
static let instance: YYSocketManager = YYSocketManager()
|
/// DisposeBag
|
private var timeDisposeBag = DisposeBag()
|
|
private var host = ""
|
private var point:Int32!
|
|
class func shared(host:String,port:Int32) -> YYSocketManager {
|
instance.host = host
|
instance.point = port
|
return instance
|
}
|
|
override init() {
|
super.init()
|
initNotificationCenter()
|
}
|
|
|
func initNotificationCenter() {
|
NotificationCenter.default.addObserver(self, selector: #selector(detectSocketServiceState(notif:)), name: NSNotification.Name(rawValue: kNotificationSocketServiceState), object: nil)
|
NotificationCenter.default.addObserver(self, selector: #selector(detectSocketPacketResponse(notif:)), name: NSNotification.Name(rawValue: kNotificationSocketPacketResponse), object: nil)
|
}
|
|
/// 开始
|
func startSocket(host:String,port:Int32) {
|
if !RHSocketService.sharedInstance().isRunning{
|
//方便多次观察,先停止之前的连接
|
YYSocketManager.shared(host: host, port: port).stopSocket()
|
let encoder = RHSocketVariableLengthEncoder()
|
let decoder = RHSocketVariableLengthDecoder()
|
encoder.countOfLengthByte = 4
|
decoder.countOfLengthByte = 4
|
RHSocketService.sharedInstance().encoder = encoder
|
RHSocketService.sharedInstance().decoder = decoder
|
let param = RHSocketConnectParam()
|
param.host = host
|
param.port = Int32(point)
|
//心跳间隔
|
param.heartbeatInterval = 5
|
//设置短线后是否自动重连
|
param.autoReconnect = true
|
RHSocketService.sharedInstance().start(with: param)
|
}
|
}
|
|
/// Socket是否在运行
|
/// - Returns: BOOL
|
func isRunning() -> Bool {
|
return RHSocketService.sharedInstance().isRunning
|
}
|
|
/// 停止
|
private func stopSocket() {
|
RHSocketService.sharedInstance().stop()
|
}
|
|
//MARK: - socket状态
|
@objc func detectSocketServiceState(notif:NSNotification) {
|
if let state = notif.object {
|
if state as? Bool == true{
|
//链接成功
|
Observable<Int>.interval(RxTimeInterval.seconds(5), scheduler: MainScheduler.instance)
|
.subscribe(onNext: { [unowned self](_) in
|
print("--->心跳")
|
}).disposed(by: timeDisposeBag)
|
}else{
|
//链接失败
|
self.timeDisposeBag = DisposeBag()
|
}
|
}else{
|
//链接失败
|
self.timeDisposeBag = DisposeBag()
|
}
|
}
|
|
//MARK: - 解析接收长连接信息
|
func decodeResponse(notification:NSNotification) -> NSDictionary {
|
if notification.object != nil {
|
return (notification.object as! NSDictionary)
|
}
|
if let userInfo:Dictionary = notification.userInfo {
|
let rsp:RHSocketPacketResponse = userInfo["RHSocketPacket"] as! RHSocketPacketResponse
|
// let strEncode = CFStringConvertEncodingToNSStringEncoding(UInt32(CFStringEncodings.GB_18030_2000.rawValue))
|
|
if let data:Data = rsp.object as? Data{
|
let result = String.init(data: data, encoding: .utf8)
|
let newData = result?.data(using: String.Encoding.utf8)
|
guard let data = newData else{
|
return [:]
|
}
|
let dic = try? JSONSerialization.jsonObject(with: data, options: JSONSerialization.ReadingOptions.allowFragments)
|
if let dict:NSDictionary = dic as? NSDictionary{
|
|
return dict
|
}else{
|
return [:]
|
}
|
|
}else{
|
return [:]
|
}
|
|
}else{
|
return [:]
|
}
|
}
|
|
//MARK: - socket接收信息
|
@objc func detectSocketPacketResponse(notif:NSNotification) {
|
let dic = decodeResponse(notification: notif)
|
|
let info = SocketModel<SimpleModel>.deserialize(from: dic)
|
|
guard let model = info else {return}
|
}
|
}
|
|
|
struct SocketModel<T:HandyJSON>:HandyJSON{
|
var code = 0
|
var msg = ""
|
var data:T?
|
var method = "" //SCAN_YARD_PUSH:场地预约扫码
|
}
|