杨锴
2025-05-11 7453d2d0cef415b34323d1b91e6cfa4a6ba31178
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
//
//  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:场地预约扫码
}