CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutSign UpSign In
sagemathinc

Real-time collaboration for Jupyter Notebooks, Linux Terminals, LaTeX, VS Code, R IDE, and more,
all in one place.

GitHub Repository: sagemathinc/cocalc
Path: blob/master/src/packages/sync-client/scratch/ws.ts
Views: 687
1
/*
2
Create a very, very simple example using the nodejs ws library of a client
3
and server talking to each other via a websocket. The client and server
4
should both be nodejs processes (no web browser involved!).
5
6
The simple code below works fine and accomplishes the goal above.
7
8
In one node shell:
9
10
> wss = require('./dist/ws').server();
11
Server Received message: hi
12
13
In another:
14
15
> ws = require('./dist/ws').client();
16
> Client Received message: Welcome to the WebSocket server!
17
> ws.send("hi")
18
undefined
19
*/
20
21
import WebSocket from "ws";
22
23
export function server() {
24
const wss = new WebSocket.Server({ port: 8080 });
25
wss.on("connection", (ws) => {
26
console.log("Client connected");
27
ws.send("Welcome to the WebSocket server!");
28
ws.onmessage = (event) => {
29
console.log(`Server Received message: ${event.data}`);
30
};
31
});
32
return wss;
33
}
34
35
export function client() {
36
const ws = new WebSocket("ws://127.0.0.1:8080");
37
ws.onmessage = (event) => {
38
console.log(`Client Received message: ${event.data}`);
39
};
40
return ws;
41
}
42
43
44