import { WebSocketServer } from "https://deno.land/x/websocket@v0.1.3/mod.ts"; import { isServerMessage, isTextMessage, MessageType, } from "./lib/types/ServerMessage.ts"; const port = 8989; const timeout = 15000; const server = new WebSocketServer(port); console.log("listening on port: " + port); server.on("connection", function connection(socket) { function close() { socket.send("closing connection due to inactivity"); socket.close(); } socket.on("message", function (rawMessage: string) { console.log("message: " + rawMessage); const message = JSON.parse(rawMessage); if (!isServerMessage(message)) { console.error(`Unexpected message received from client \`${message}\``); } if (isTextMessage(message)) { socket.send( JSON.stringify({ type: MessageType.TEXT, date: Date.now(), author: "ECHO Service", content: message.content, }), ); } clearTimeout(closeTimeout); closeTimeout = setTimeout(close, timeout); }); socket.on("close", function close() { console.log("closed a connection"); }); console.log("new client connected!"); socket.send("connected"); let closeTimeout = setTimeout(close, timeout); });