Path: blob/master/src/packages/sync-client/scratch/ws.ts
1503 views
/*1Create a very, very simple example using the nodejs ws library of a client2and server talking to each other via a websocket. The client and server3should both be nodejs processes (no web browser involved!).45The simple code below works fine and accomplishes the goal above.67In one node shell:89> wss = require('./dist/ws').server();10Server Received message: hi1112In another:1314> ws = require('./dist/ws').client();15> Client Received message: Welcome to the WebSocket server!16> ws.send("hi")17undefined18*/1920import WebSocket from "ws";2122export function server() {23const wss = new WebSocket.Server({ port: 8080 });24wss.on("connection", (ws) => {25console.log("Client connected");26ws.send("Welcome to the WebSocket server!");27ws.onmessage = (event) => {28console.log(`Server Received message: ${event.data}`);29};30});31return wss;32}3334export function client() {35const ws = new WebSocket("ws://127.0.0.1:8080");36ws.onmessage = (event) => {37console.log(`Client Received message: ${event.data}`);38};39return ws;40}41424344