Files
wren/example/chat_server.wren
T
retoor 8f1d13a86b feat: add networking module with TCP Socket/Server and example applications
Implement a full-featured `net` module supporting TCP `Socket` and `Server` classes via libuv, including example applications (chat server, echo server, HTTP client/server, file explorer, system dashboard) and benchmark scripts (fibonacci, n-body). Add GEMINI.md project documentation and Stderr class to io module.
2026-01-24 08:57:59 +00:00

58 lines
1.4 KiB
JavaScript
Vendored

// retoor <retoor@molodetz.nl>
import "net" for Server, Socket
import "scheduler" for Scheduler
class ChatServer {
construct new(port) {
_port = port
_clients = []
_server = Server.bind("0.0.0.0", port)
System.print("Chat Server listening on port %(_port)")
}
run() {
while (true) {
var socket = _server.accept()
handleNewClient(socket)
}
}
handleNewClient(socket) {
_clients.add(socket)
var id = _clients.count
System.print("Client %(id) connected. Total: %(_clients.count)")
Fiber.new {
broadcast("Client %(id) joined the chat!\n", socket)
while (true) {
var message = socket.read()
if (message == null || message == "") break
System.print("Client %(id): %(message.trim())")
broadcast("Client %(id): %(message)", socket)
}
System.print("Client %(id) disconnected.")
_clients.remove(socket)
socket.close()
broadcast("Client %(id) left the chat.\n", null)
}.call()
}
broadcast(message, sender) {
for (client in _clients) {
if (client != sender) {
// We use a separate fiber for each write to prevent one slow
// client from blocking the broadcast to others
Fiber.new {
client.write(message)
}.call()
}
}
}
}
var server = ChatServer.new(7070)
server.run()