I'm trying to design a SwiftNIO server where multiple clients (like 2 or 3) can connect to the server, and when connected, they can all receive information from the server.
To do this, I create a ServerHandler
class which is shared & added to each pipeline of connected clients.
let group = MultiThreadedEventLoopGroup(numberOfThreads: 2)
let handler = ServerHandler()
let bootstrap = ServerBootstrap(group: group)
.serverChannelOption(ChannelOptions.backlog, value: 2)
.serverChannelOption(ChannelOptions.socketOption(.so_reuseaddr), value: 1)
.childChannelInitializer { $0.pipeline.addHandler(handler) }
.childChannelOption(ChannelOptions.socketOption(.so_reuseaddr), value: 1)
The above code is inspired from https://github.com/apple/swift-nio/blob/main/Sources/NIOChatServer/main.swift
In the ServerHandler
class, whenever a new client connects, that channel is added to an array. Then, when I'm ready to send data to all the clients, I just loop through the channels in the ServerHandler
, and call writeAndFlush
.
This seems to work pretty well, but there are a couple things I'm concerned about:
- It seems that creating a shared handler is not really recommended, and you should instead create a new handler for each client. But then, how would I access all the client channels which I need to send data to? (I send data at times determined by the UI)
- Why does
Channel.write
not seem to do anything? My client is unable to receive any data if I useChannel.write
instead ofwriteAndFlush
in the server.
I apologize if these questions are stupid, I just started with SwiftNIO
and networking in general very recently.
If anybody could give me some insight, that would be awesome.