Design Patterns|Practical Solutions for Socket.IO Client Library Challenges
Discover how to resolve common challenges in encapsulating Socket.IO Client Library using proven Design Patterns, enhancing code maintainability and scalability for developers facing similar integration issues.
This post was translated with AI assistance — let me know if anything sounds off!
Table of Contents
Practical Application Records of Design Patterns
Problem Scenarios Encountered When Encapsulating the Socket.IO Client Library and Design Patterns Applied to Solutions
Photo by Daniel McCullough
Preface
This article records real development scenarios where Design Patterns were used to solve problems. It covers the background of the requirements, the actual problem scenarios (What?), why applying Patterns is necessary (Why?), and how to implement them (How?). It is recommended to read from the beginning for better coherence.
This article introduces four development scenarios encountered for this requirement and the application of seven Design Patterns to solve these scenarios.
Background
Organization Structure
Our company split into multiple Feature Teams and a Platform Team this year; the former mainly handles user-side requirements, while the Platform Team works internally within the company. One of its tasks is technology adoption, infrastructure, and systematic integration to pave the way for Feature Teams when developing their requirements.
Current Requirements
Feature Teams want to change the original messaging feature (fetching message data by calling APIs on page load, requiring refresh to update messages) to real-time communication (able to receive the latest messages instantly and send messages in real time).
Platform Team Work
The Platform Team focuses not only on the current real-time communication needs but also on long-term development and reusability. After evaluation, the WebSocket bidirectional communication mechanism is indispensable in modern apps. Beyond this requirement, there will be many opportunities to use it in the future. With sufficient human resources, the team is committed to assisting in designing and developing the interface.
Goal:
Encapsulating Pinkoi Server Side and Socket.IO Communication, Authentication Logic
Encapsulate the tedious operations of Socket.IO, providing an extensible and user-friendly interface based on Pinkoi’s business requirements
Unified Cross-Platform Interface (The Socket.IO Android and iOS Client Side Libraries support different features and interfaces)
Feature side does not need to understand the Socket.IO mechanism
Feature side does not need to manage complex connection states
Future WebSocket bidirectional communication needs can be directly supported
Time and Manpower:
One person dedicated to iOS and one to Android respectively
Development Schedule: Duration 3 weeks
Technical Details
This feature will be supported on Web, iOS, and Android platforms; it requires introducing the WebSocket bidirectional communication protocol. The backend plans to use the Socket.io service directly.
First of all, Socket != WebSocket
For details about Socket and WebSocket technologies, please refer to the following two articles:
In short:
1
2
Socket is an abstract interface for the TCP/UDP transport layer, while WebSocket is a transport protocol at the application layer.
The relationship between Socket and WebSocket is like that between a dog and a hot dog—no relation.
Socket.IO is an abstraction layer built on top of Engine.IO, which itself wraps WebSocket usage. Each layer only handles communication between the layer above and below it, disallowing direct operations across layers (e.g., Socket.IO does not directly operate the WebSocket connection).
Socket.IO/Engine.IO implements many convenient features beyond basic WebSocket connections (e.g., offline event sending mechanism, HTTP-like request mechanism, Room/Group mechanism, etc.).
The main responsibility of the Platform Team layer is to bridge the logic between Socket.IO and the Pinkoi Server Side, providing support for upper Feature Teams during feature development.
Socket.IO Swift Client has pitfalls
It has not been updated for a long time (the latest version is still from 2019), so it is unclear if it is still maintained.
Client & Server Side Socket IO versions must match. On the Server Side, you can add
{allowEIO3: true}, or specify the same version on the Client Side using.version.
Otherwise, the connection will fail no matter what.Naming conventions, interfaces, and official website examples often do not match.
Socket.io official examples are all based on Web, but the Swift Client does not necessarily support all features shown on the official site.
In this implementation, we found that the iOS Library does not provide an offline event sending mechanism
(which we implemented ourselves, please continue reading).
It is recommended to experiment first to see if the desired mechanism is supported before adopting Socket.IO.
Socket.IO Swift Client is a wrapper based on the Starscream WebSocket Library and can fallback to Starscream when necessary.
1
Background information ends here. Now, let's get to the main topic.
Design Patterns
Design patterns are essentially solutions to common problems in software design. You don’t have to use design patterns to develop, design patterns may not fit all scenarios, and no one says you can’t create your own new design patterns.
The Catalog of Design Patterns
However, the existing design patterns (The 23 Gang of Four Design Patterns) are common knowledge in software design. When mentioning a XXX Pattern, everyone immediately envisions the corresponding architectural blueprint, requiring little explanation. This also makes subsequent maintenance easier to understand and is a proven industry method that rarely requires time to review object dependency issues. Choosing the right pattern for the right scenario can reduce communication and maintenance costs and improve development efficiency.
Design patterns can be combined, but it is not recommended to drastically modify existing patterns, forcefully apply them without reason, or use patterns outside their intended category (e.g., using the Chain of Responsibility pattern to create objects). Doing so defeats their purpose and may cause confusion for future maintainers.
Design Patterns Mentioned in This Article:
Each will be explained later one by one: the scenario used and why it was chosen.
This article focuses on the application of Design Patterns rather than Socket.IO operations. Some examples are simplified for clarity and are not suitable for real Socket.IO encapsulation.
Due to space limitations, this article will not detail the architecture of each design pattern. Please click on the links for each pattern to understand their structures before continuing.
The demo code will be written in Swift.
Requirement Scenario 1.
What?
Reuse the same object when requesting a Connection with the same Path on different pages or Objects.
Connection should be an abstract interface, not directly dependent on the Socket.IO Object
Why?
Reduce memory overhead and the time and traffic costs of repeated connections.
Reserve space for future replacement with other frameworks
How?
Singleton Pattern: A creational pattern that ensures a class has only one instance.
Flyweight Pattern: A structural pattern that shares common states among multiple objects for reuse.
Factory Pattern: A creational pattern that abstracts the object creation method, allowing it to be replaced externally.
Real Case Usage:
Singleton Pattern: The
ConnectionManagerexists as a single instance throughout the App Lifecycle, managing access toConnectionobjects.Flyweight Pattern: The
ConnectionPoolis a shared pool of Connections. It provides a unified way to get a Connection from the pool, including logic to return an existing Connection if the URL Path matches.
ConnectionHandleracts as an external operator and state manager for theConnection.Factory Pattern: The
ConnectionFactoryworks with the Flyweight Pattern above to create a newConnectionvia this factory interface when no reusable connection is found in the pool.
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
import Combine
import Foundation
protocol Connection {
var url: URL {get}
var id: UUID {get}
init(url: URL)
func connect()
func disconnect()
func sendEvent(_ event: String)
func onEvent(_ event: String) -> AnyPublisher<Data?, Never>
}
protocol ConnectionFactory {
func create(url: URL) -> Connection
}
class ConnectionPool {
private let connectionFactory: ConnectionFactory
private var connections: [Connection] = []
init(connectionFactory: ConnectionFactory) {
self.connectionFactory = connectionFactory
}
func getOrCreateConnection(url: URL) -> Connection {
if let connection = connections.first(where: { $0.url == url }) {
return connection
} else {
let connection = connectionFactory.create(url: url)
connections.append(connection)
return connection
}
}
}
class ConnectionHandler {
private let connection: Connection
init(connection: Connection) {
self.connection = connection
}
func getConnectionUUID() -> UUID {
return connection.id
}
}
class ConnectionManager {
static let shared = ConnectionManager(connectionPool: ConnectionPool(connectionFactory: SIOConnectionFactory()))
private let connectionPool: ConnectionPool
private init(connectionPool: ConnectionPool) {
self.connectionPool = connectionPool
}
//
func requestConnectionHandler(url: URL) -> ConnectionHandler {
let connection = connectionPool.getOrCreateConnection(url: url)
return ConnectionHandler(connection: connection)
}
}
// Socket.IO Implementation
class SIOConnection: Connection {
let url: URL
let id: UUID = UUID()
required init(url: URL) {
self.url = url
//
}
func connect() {
//
}
func disconnect() {
//
}
func sendEvent(_ event: String) {
//
}
func onEvent(_ event: String) -> AnyPublisher<Data?, Never> {
//
return PassthroughSubject<Data?, Never>().eraseToAnyPublisher()
}
}
class SIOConnectionFactory: ConnectionFactory {
func create(url: URL) -> Connection {
//
return SIOConnection(url: url)
}
}
//
print(ConnectionManager.shared.requestConnectionHandler(url: URL(string: "wss://pinkoi.com/1")!).getConnectionUUID().uuidString)
print(ConnectionManager.shared.requestConnectionHandler(url: URL(string: "wss://pinkoi.com/1")!).getConnectionUUID().uuidString)
print(ConnectionManager.shared.requestConnectionHandler(url: URL(string: "wss://pinkoi.com/2")!).getConnectionUUID().uuidString)
// output:
// D99F5429-1C6D-4EB5-A56E-9373D6F37307
// D99F5429-1C6D-4EB5-A56E-9373D6F37307
// 599CF16F-3D7C-49CF-817B-5A57C119FE31
Requirement Scenario 2.
What?
As described in the background technical details, the Socket.IO Swift Client’s Send Event does not support offline sending (while the Web/Android versions of the library do), so the iOS side needs to implement this feature independently.
1
The amazing thing is that the Socket.IO Swift Client - onEvent supports offline subscription.
Why?
Cross-Platform Feature Unification
The code is easy to understand
How?
- Command Pattern: A behavioral pattern that encapsulates operations into objects, allowing queuing, delaying, canceling, and other batch actions.
- Command Pattern:
SIOManageris the lowest-level wrapper for communicating with Socket.IO. Itssendandrequestmethods operate on Socket.IO Send Events. When the current Socket.IO is disconnected, the request parameters are placed intobufferedCommands. Once reconnected, these commands are processed one by one (First In First Out).
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
protocol BufferedCommand {
var sioManager: SIOManagerSpec? { get set }
var event: String { get }
func execute()
}
struct SendBufferedCommand: BufferedCommand {
let event: String
weak var sioManager: SIOManagerSpec?
func execute() {
sioManager?.send(event)
}
}
struct RequestBufferedCommand: BufferedCommand {
let event: String
let callback: (Data?) -> Void
weak var sioManager: SIOManagerSpec?
func execute() {
sioManager?.request(event, callback: callback)
}
}
protocol SIOManagerSpec: AnyObject {
func connect()
func disconnect()
func onEvent(event: String, callback: @escaping (Data?) -> Void)
func send(_ event: String)
func request(_ event: String, callback: @escaping (Data?) -> Void)
}
enum ConnectionState {
case created
case connected
case disconnected
case reconnecting
case released
}
class SIOManager: SIOManagerSpec {
var state: ConnectionState = .disconnected {
didSet {
if state == .connected {
executeBufferedCommands()
}
}
}
private var bufferedCommands: [BufferedCommand] = []
func connect() {
state = .connected
}
func disconnect() {
state = .disconnected
}
func send(_ event: String) {
guard state == .connected else {
appendBufferedCommands(connectionCommand: SendBufferedCommand(event: event, sioManager: self))
return
}
print("Send:\(event)")
}
func request(_ event: String, callback: @escaping (Data?) -> Void) {
guard state == .connected else {
appendBufferedCommands(connectionCommand: RequestBufferedCommand(event: event, callback: callback, sioManager: self))
return
}
print("request:\(event)")
}
func onEvent(event: String, callback: @escaping (Data?) -> Void) {
//
}
func appendBufferedCommands(connectionCommand: BufferedCommand) {
bufferedCommands.append(connectionCommand)
}
func executeBufferedCommands() {
// First in, first out
bufferedCommands.forEach { connectionCommand in
connectionCommand.execute()
}
bufferedCommands.removeAll()
}
func removeAllBufferedCommands() {
bufferedCommands.removeAll()
}
}
let manager = SIOManager()
manager.send("send_event_1")
manager.send("send_event_2")
manager.request("request_event_1") { _ in
//
}
manager.state = .connected
Similarly, it can also be implemented on onEvent.
Extension: You can also apply the Proxy Pattern, treating the Buffer functionality as a type of Proxy.
Requirement Scenario 3.
What?
Connection has multiple states, with ordered transitions between states, and each state allows different operations.
Created: The object is created, allowing transition to ->
Connectedor directly toDisconnectedConnected: Connected to Socket.IO, allows ->
DisconnectedDisconnected: Disconnected from Socket.IO, allows ->
Reconnectiong,ReleasedReconnectiong: Attempting to reconnect to Socket.IO, allowed states ->
Connected,DisconnectedReleased: The object has been marked for memory deallocation and does not allow any operations or state transitions.
Why?
The logic and representation of states and state transitions are complex.
Each state must restrict certain operations (e.g., when State = Released, calling Send Event is not allowed). Using if…else directly makes the code difficult to maintain and read.
How?
Finite State Machine: Manage transitions between states
State Pattern: A behavioral pattern that handles different responses based on the object’s state changes
Finite State Machine:
SIOConnectionStateMachineis the state machine implementation,currentSIOConnectionStaterepresents the current state, andcreated,connected,disconnected,reconnecting,releasedlist the possible states this machine can switch to.
enterXXXState() throwshandles the allowed and disallowed (throw error) transitions when entering a certain state from the current state.State Pattern:
SIOConnectionStateis the abstract interface for all operations used by the states.
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
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
protocol SIOManagerSpec: AnyObject {
func connect()
func disconnect()
func onEvent(event: String, callback: @escaping (Data?) -> Void)
func send(_ event: String)
func request(_ event: String, callback: @escaping (Data?) -> Void)
}
enum ConnectionState {
case created
case connected
case disconnected
case reconnecting
case released
}
class SIOManager: SIOManagerSpec {
var state: ConnectionState = .disconnected {
didSet {
if state == .connected {
executeBufferedCommands()
}
}
}
private var bufferedCommands: [BufferedCommand] = []
func connect() {
state = .connected
}
func disconnect() {
state = .disconnected
}
func send(_ event: String) {
guard state == .connected else {
appendBufferedCommands(connectionCommand: SendBufferedCommand(event: event, sioManager: self))
return
}
print("Send:\(event)")
}
func request(_ event: String, callback: @escaping (Data?) -> Void) {
guard state == .connected else {
appendBufferedCommands(connectionCommand: RequestBufferedCommand(event: event, callback: callback, sioManager: self))
return
}
print("request:\(event)")
}
func onEvent(event: String, callback: @escaping (Data?) -> Void) {
//
}
func appendBufferedCommands(connectionCommand: BufferedCommand) {
bufferedCommands.append(connectionCommand)
}
func executeBufferedCommands() {
// First in, first out
bufferedCommands.forEach { connectionCommand in
connectionCommand.execute()
}
bufferedCommands.removeAll()
}
func removeAllBufferedCommands() {
bufferedCommands.removeAll()
}
}
let manager = SIOManager()
manager.send("send_event_1")
manager.send("send_event_2")
manager.request("request_event_1") { _ in
//
}
manager.state = .connected
//
class SIOConnectionStateMachine {
private(set) var currentSIOConnectionState: SIOConnectionState!
private var created: SIOConnectionState!
private var connected: SIOConnectionState!
private var disconnected: SIOConnectionState!
private var reconnecting: SIOConnectionState!
private var released: SIOConnectionState!
init() {
self.created = SIOConnectionCreatedState(stateMachine: self)
self.connected = SIOConnectionConnectedState(stateMachine: self)
self.disconnected = SIOConnectionDisconnectedState(stateMachine: self)
self.reconnecting = SIOConnectionReconnectingState(stateMachine: self)
self.released = SIOConnectionReleasedState(stateMachine: self)
self.currentSIOConnectionState = created
}
func enterConnected() throws {
if [created.connectionState, reconnecting.connectionState].contains(currentSIOConnectionState.connectionState) {
enter(connected)
} else {
throw SIOConnectionStateMachineError("\(currentSIOConnectionState.connectionState) can't enter to Connected")
}
}
func enterDisconnected() throws {
if [created.connectionState, connected.connectionState, reconnecting.connectionState].contains(currentSIOConnectionState.connectionState) {
enter(disconnected)
} else {
throw SIOConnectionStateMachineError("\(currentSIOConnectionState.connectionState) can't enter to Disconnected")
}
}
func enterReconnecting() throws {
if [disconnected.connectionState].contains(currentSIOConnectionState.connectionState) {
enter(reconnecting)
} else {
throw SIOConnectionStateMachineError("\(currentSIOConnectionState.connectionState) can't enter to Reconnecting")
}
}
func enterReleased() throws {
if [disconnected.connectionState].contains(currentSIOConnectionState.connectionState) {
enter(released)
} else {
throw SIOConnectionStateMachineError("\(currentSIOConnectionState.connectionState) can't enter to Released")
}
}
private func enter(_ state: SIOConnectionState) {
currentSIOConnectionState = state
}
}
protocol SIOConnectionState {
var connectionState: ConnectionState { get }
var stateMachine: SIOConnectionStateMachine { get }
init(stateMachine: SIOConnectionStateMachine)
func onConnected() throws
func onDisconnected() throws
func connect(socketManager: SIOManagerSpec) throws
func disconnect(socketManager: SIOManagerSpec) throws
func release(socketManager: SIOManagerSpec) throws
func request(socketManager: SIOManagerSpec, event: String, callback: @escaping (Data?) -> Void) throws
func onEvent(socketManager: SIOManagerSpec, event: String, callback: @escaping (Data?) -> Void) throws
func send(socketManager: SIOManagerSpec, event: String) throws
}
struct SIOConnectionStateMachineError: Error {
let message: String
init(_ message: String) {
self.message = message
}
var localizedDescription: String {
return message
}
}
class SIOConnectionCreatedState: SIOConnectionState {
let connectionState: ConnectionState = .created
let stateMachine: SIOConnectionStateMachine
required init(stateMachine: SIOConnectionStateMachine) {
self.stateMachine = stateMachine
}
func onConnected() throws {
try stateMachine.enterConnected()
}
func onDisconnected() throws {
try stateMachine.enterDisconnected()
}
func release(socketManager: SIOManagerSpec) throws {
throw SIOConnectionStateMachineError("ConnectedState can't release!")
}
func onEvent(socketManager: SIOManagerSpec, event: String, callback: @escaping (Data?) -> Void) throws {
// allow
// can use Helper to reduce the repeating code
// e.g. helper.XXX(socketManager: SIOManagerSpec, ....)
}
func request(socketManager: SIOManagerSpec, event: String, callback: @escaping (Data?) -> Void) throws {
// allow
// can use Helper to reduce the repeating code
// e.g. helper.XXX(socketManager: SIOManagerSpec, ....)
}
func send(socketManager: SIOManagerSpec, event: String) throws {
// allow
// can use Helper to reduce the repeating code
// e.g. helper.XXX(socketManager: SIOManagerSpec, ....)
}
func connect(socketManager: SIOManagerSpec) throws {
// allow
// can use Helper to reduce the repeating code
// e.g. helper.XXX(socketManager: SIOManagerSpec, ....)
}
func disconnect(socketManager: SIOManagerSpec) throws {
throw SIOConnectionStateMachineError("CreatedState can't disconnect!")
}
}
class SIOConnectionConnectedState: SIOConnectionState {
let connectionState: ConnectionState = .connected
let stateMachine: SIOConnectionStateMachine
required init(stateMachine: SIOConnectionStateMachine) {
self.stateMachine = stateMachine
}
func onConnected() throws {
//
}
func onDisconnected() throws {
try stateMachine.enterDisconnected()
}
func release(socketManager: SIOManagerSpec) throws {
throw SIOConnectionStateMachineError("ConnectedState can't release!")
}
func onEvent(socketManager: SIOManagerSpec, event: String, callback: @escaping (Data?) -> Void) throws {
// allow
// can use Helper to reduce the repeating code
// e.g. helper.XXX(socketManager: SIOManagerSpec, ....)
}
func request(socketManager: SIOManagerSpec, event: String, callback: @escaping (Data?) -> Void) throws {
// allow
// can use Helper to reduce the repeating code
// e.g. helper.XXX(socketManager: SIOManagerSpec, ....)
}
func send(socketManager: SIOManagerSpec, event: String) throws {
// allow
// can use Helper to reduce the repeating code
// e.g. helper.XXX(socketManager: SIOManagerSpec, ....)
}
func connect(socketManager: SIOManagerSpec) throws {
throw SIOConnectionStateMachineError("ConnectedState can't connect!")
}
func disconnect(socketManager: SIOManagerSpec) throws {
// allow
// can use Helper to reduce the repeating code
// e.g. helper.XXX(socketManager: SIOManagerSpec, ....)
}
}
class SIOConnectionDisconnectedState: SIOConnectionState {
let connectionState: ConnectionState = .disconnected
let stateMachine: SIOConnectionStateMachine
required init(stateMachine: SIOConnectionStateMachine) {
self.stateMachine = stateMachine
}
func onConnected() throws {
try stateMachine.enterConnected()
}
func onDisconnected() throws {
//
}
func release(socketManager: SIOManagerSpec) throws {
try stateMachine.enterReleased()
// allow
// can use Helper to reduce the repeating code
// e.g. helper.XXX(socketManager: SIOManagerSpec, ....)
}
func onEvent(socketManager: SIOManagerSpec, event: String, callback: @escaping (Data?) -> Void) throws {
// allow
// can use Helper to reduce the repeating code
// e.g. helper.XXX(socketManager: SIOManagerSpec, ....)
}
func request(socketManager: SIOManagerSpec, event: String, callback: @escaping (Data?) -> Void) throws {
// allow
// can use Helper to reduce the repeating code
// e.g. helper.XXX(socketManager: SIOManagerSpec, ....)
}
func send(socketManager: SIOManagerSpec, event: String) throws {
// allow
// can use Helper to reduce the repeating code
// e.g. helper.XXX(socketManager: SIOManagerSpec, ....)
}
func connect(socketManager: SIOManagerSpec) throws {
try stateMachine.enterReconnecting()
// allow
// can use Helper to reduce the repeating code
// e.g. helper.XXX(socketManager: SIOManagerSpec, ....)
}
func disconnect(socketManager: SIOManagerSpec) throws {
// allow
// can use Helper to reduce the repeating code
// e.g. helper.XXX(socketManager: SIOManagerSpec, ....)
}
}
class SIOConnectionReconnectingState: SIOConnectionState {
let connectionState: ConnectionState = .reconnecting
let stateMachine: SIOConnectionStateMachine
required init(stateMachine: SIOConnectionStateMachine) {
self.stateMachine = stateMachine
}
func onConnected() throws {
try stateMachine.enterConnected()
}
func onDisconnected() throws {
try stateMachine.enterDisconnected()
}
func release(socketManager: SIOManagerSpec) throws {
throw SIOConnectionStateMachineError("ReconnectState can't release!")
}
func onEvent(socketManager: SIOManagerSpec, event: String, callback: @escaping (Data?) -> Void) throws {
// allow
// can use Helper to reduce the repeating code
// e.g. helper.XXX(socketManager: SIOManagerSpec, ....)
}
func request(socketManager: SIOManagerSpec, event: String, callback: @escaping (Data?) -> Void) throws {
// allow
// can use Helper to reduce the repeating code
// e.g. helper.XXX(socketManager: SIOManagerSpec, ....)
}
func send(socketManager: SIOManagerSpec, event: String) throws {
// allow
// can use Helper to reduce the repeating code
// e.g. helper.XXX(socketManager: SIOManagerSpec, ....)
}
func connect(socketManager: SIOManagerSpec) throws {
throw SIOConnectionStateMachineError("ReconnectState can't connect!")
}
func disconnect(socketManager: SIOManagerSpec) throws {
// allow
// can use Helper to reduce the repeating code
// e.g. helper.XXX(socketManager: SIOManagerSpec, ....)
}
}
class SIOConnectionReleasedState: SIOConnectionState {
let connectionState: ConnectionState = .released
let stateMachine: SIOConnectionStateMachine
required init(stateMachine: SIOConnectionStateMachine) {
self.stateMachine = stateMachine
}
func onConnected() throws {
throw SIOConnectionStateMachineError("ReleasedState can't onConnected!")
}
func onDisconnected() throws {
throw SIOConnectionStateMachineError("ReleasedState can't onDisconnected!")
}
func release(socketManager: SIOManagerSpec) throws {
throw SIOConnectionStateMachineError("ReleasedState can't release!")
}
func request(socketManager: SIOManagerSpec, event: String, callback: @escaping (Data?) -> Void) throws {
throw SIOConnectionStateMachineError("ReleasedState can't request!")
}
func onEvent(socketManager: SIOManagerSpec, event: String, callback: @escaping (Data?) -> Void) throws {
throw SIOConnectionStateMachineError("ReleasedState can't receiveOn!")
}
func send(socketManager: SIOManagerSpec, event: String) throws {
throw SIOConnectionStateMachineError("ReleasedState can't send!")
}
func connect(socketManager: SIOManagerSpec) throws {
throw SIOConnectionStateMachineError("ReleasedState can't connect!")
}
func disconnect(socketManager: SIOManagerSpec) throws {
throw SIOConnectionStateMachineError("ReleasedState can't disconnect!")
}
}
do {
let stateMachine = SIOConnectionStateMachine()
// mock on socket.io connect:
// socketIO.on(connect){
try stateMachine.currentSIOConnectionState.onConnected()
try stateMachine.currentSIOConnectionState.send(socketManager: manager, event: "test")
try stateMachine.currentSIOConnectionState.release(socketManager: manager)
try stateMachine.currentSIOConnectionState.send(socketManager: manager, event: "test")
// }
} catch {
print("error: \(error)")
}
// output:
// error: SIOConnectionStateMachineError(message: "ConnectedState can\'t release!")
Requirement Scenario 3.
What?
Combining scenarios 1 and 2, with the ConnectionPool flyweight pool and State Pattern for state management; we continue to extend. As stated in the background goal, the Feature side does not need to manage the underlying Connection mechanism. Therefore, we created a poller (named ConnectionKeeper) that periodically scans the strongly held Connection objects in the ConnectionPool and performs actions when the following situations occur:
Connectionis in use and the status is notConnected: change the status toReconnectingand attempt to reconnectConnectionis no longer in use and its status isConnected: change the status toDisconnectedConnectionis no longer in use and its state isDisconnected: change the state toReleasedand remove it from theConnectionPool
Why?
Three operations have a hierarchical relationship and are mutually exclusive (disconnected -> released or reconnecting)
Flexible swapping and adding condition handling
Without encapsulation, the three checks and operations can only be written directly within the method (making it difficult to test the logic).
e.g:
1
2
3
4
5
6
7
if !connection.isOccupie() && connection.state == .connected then
... connection.disconnected()
else if !connection.isOccupie() && state == .released then
... connection.release()
else if connection.isOccupie() && state == .disconnected then
... connection.reconnecting()
end
How?
- Chain Of Responsibility: A behavioral pattern that, as the name suggests, is a chain where each node has a corresponding operation. After receiving input data, a node decides whether to handle it or pass it to the next node. Another real-world example is the iOS Responder Chain.
By definition, the Chain of Responsibility Pattern does not allow a node to process the data and then pass it to the next node for further processing. Either complete the processing or do not process at all.
If the above scenario is more suitable, it should be the Interceptor Pattern.
- Chain of responsibility:
ConnectionKeeperHandleris the abstract node of the chain. ThecanExcutemethod is specially extracted to avoid the situation where this node handles the task but then wants to call the next node to continue execution. Thehandlemethod links the nodes in the chain, andexcutedefines the logic of how to process the task if it is handled.
ConnectionKeeperHandlerContextis used to store the necessary data, whereisOccupieindicates whether the Connection is currently in use.
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
enum ConnectionState {
case created
case connected
case disconnected
case reconnecting
case released
}
protocol Connection {
var connectionState: ConnectionState {get}
var url: URL {get}
var id: UUID {get}
init(url: URL)
func connect()
func reconnect()
func disconnect()
func sendEvent(_ event: String)
func onEvent(_ event: String) -> AnyPublisher<Data?, Never>
}
// Socket.IO Implementation
class SIOConnection: Connection {
let connectionState: ConnectionState = .created
let url: URL
let id: UUID = UUID()
required init(url: URL) {
self.url = url
//
}
func connect() {
//
}
func disconnect() {
//
}
func reconnect() {
//
}
func sendEvent(_ event: String) {
//
}
func onEvent(_ event: String) -> AnyPublisher<Data?, Never> {
//
return PassthroughSubject<Data?, Never>().eraseToAnyPublisher()
}
}
//
struct ConnectionKeeperHandlerContext {
let connection: Connection
let isOccupie: Bool
}
protocol ConnectionKeeperHandler {
var nextHandler: ConnectionKeeperHandler? { get set }
func handle(context: ConnectionKeeperHandlerContext)
func execute(context: ConnectionKeeperHandlerContext)
func canExcute(context: ConnectionKeeperHandlerContext) -> Bool
}
extension ConnectionKeeperHandler {
func handle(context: ConnectionKeeperHandlerContext) {
if canExcute(context: context) {
execute(context: context)
} else {
nextHandler?.handle(context: context)
}
}
}
class DisconnectedConnectionKeeperHandler: ConnectionKeeperHandler {
var nextHandler: ConnectionKeeperHandler?
func execute(context: ConnectionKeeperHandlerContext) {
context.connection.disconnect()
}
func canExcute(context: ConnectionKeeperHandlerContext) -> Bool {
if context.connection.connectionState == .connected && !context.isOccupie {
return true
}
return false
}
}
class ReconnectConnectionKeeperHandler: ConnectionKeeperHandler {
var nextHandler: ConnectionKeeperHandler?
func execute(context: ConnectionKeeperHandlerContext) {
context.connection.reconnect()
}
func canExcute(context: ConnectionKeeperHandlerContext) -> Bool {
if context.connection.connectionState == .disconnected && context.isOccupie {
return true
}
return false
}
}
class ReleasedConnectionKeeperHandler: ConnectionKeeperHandler {
var nextHandler: ConnectionKeeperHandler?
func execute(context: ConnectionKeeperHandlerContext) {
context.connection.disconnect()
}
func canExcute(context: ConnectionKeeperHandlerContext) -> Bool {
if context.connection.connectionState == .disconnected && !context.isOccupie {
return true
}
return false
}
}
let connection = SIOConnection(url: URL(string: "wss://pinkoi.com")!)
let disconnectedHandler = DisconnectedConnectionKeeperHandler()
let reconnectHandler = ReconnectConnectionKeeperHandler()
let releasedHandler = ReleasedConnectionKeeperHandler()
disconnectedHandler.nextHandler = reconnectHandler
reconnectHandler.nextHandler = releasedHandler
disconnectedHandler.handle(context: ConnectionKeeperHandlerContext(connection: connection, isOccupie: false))
Requirement Scenario 4.
What?
The Connection we encapsulate needs to be set up before use, such as providing the URL Path, configuring settings, and so on.
Why?
Flexible addition and removal of construction openings
Reusable Construction Logic
Without encapsulation, external code may operate the class in unintended ways.
e.g.:
1
2
3
4
5
6
7
8
❌
let connection = Connection()
connection.send(event) // unexpected method call, should call .connect() first
✅
let connection = Connection()
connection.connect()
connection.send(event)
// but...who knows???
How?
- Builder Pattern: A creational pattern that enables step-by-step object construction and reuse of building methods.
- Builder Pattern:
SIOConnectionBuilderis the builder forConnection, responsible for setting and storing data used during the construction of aConnection; theConnectionConfigurationabstract interface ensures that.connect()must be called before obtaining aConnectioninstance.
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
enum ConnectionState {
case created
case connected
case disconnected
case reconnecting
case released
}
protocol Connection {
var connectionState: ConnectionState {get}
var url: URL {get}
var id: UUID {get}
init(url: URL)
func connect()
func reconnect()
func disconnect()
func sendEvent(_ event: String)
func onEvent(_ event: String) -> AnyPublisher<Data?, Never>
}
// Socket.IO Implementation
class SIOConnection: Connection {
let connectionState: ConnectionState = .created
let url: URL
let id: UUID = UUID()
required init(url: URL) {
self.url = url
//
}
func connect() {
//
}
func disconnect() {
//
}
func reconnect() {
//
}
func sendEvent(_ event: String) {
//
}
func onEvent(_ event: String) -> AnyPublisher<Data?, Never> {
//
return PassthroughSubject<Data?, Never>().eraseToAnyPublisher()
}
}
//
class SIOConnectionClient: ConnectionConfiguration {
private let url: URL
private let config: [String: Any]
init(url: URL, config: [String: Any]) {
self.url = url
self.config = config
}
func connect() -> Connection {
// set config
return SIOConnection(url: url)
}
}
protocol ConnectionConfiguration {
func connect() -> Connection
}
class SIOConnectionBuilder {
private(set) var config: [String: Any] = [:]
func setConfig(_ config: [String: Any]) -> SIOConnectionBuilder {
self.config = config
return self
}
// url is required parameter
func build(url: URL) -> ConnectionConfiguration {
return SIOConnectionClient(url: url, config: self.config)
}
}
let builder = SIOConnectionBuilder().setConfig(["test":123])
let connection1 = builder.build(url: URL(string: "wss://pinkoi.com/1")!).connect()
let connection2 = builder.build(url: URL(string: "wss://pinkoi.com/1")!).connect()
Extension: Here, you can also apply the Factory Pattern to generate SIOConnection using a factory.
Done!
These are the four scenarios encountered during the Socket.IO encapsulation and the seven Design Patterns used to solve the problems.
Finally, the complete design blueprint for this Socket.IO encapsulation is attached
The naming and examples differ slightly from the text; this diagram shows the actual design architecture. We hope the original designer can share the design concept and open source it in the future.
Who?
Who designed these and was responsible for the Socket.IO packaging project?
Sean Zheng , Android Engineer @ Pinkoi
Main architect, design pattern evaluation and application, implemented design on Android using Kotlin.
ZhgChgLi , Engineer Lead/iOS Engineer @ Pinkoi
Platform Team project leader, pair programming, implementing designs in Swift on iOS, discussing and raising questions (a.k.a. just talking), and finally writing this article to share with everyone.
Further Reading
For any questions or feedback, feel free to contact me .
This post was originally published on Medium (View original post), and automatically converted and synced by ZMediumToMarkdown.


{:target="_blank"}](/assets/78507a8de6a5/1*MAm5WPynbv7M9tdmW2lNGQ.webp)









