WebSocket server and client code examples.The ws library is used.
Step: 1 Install ws
npm install ws
Step 2: Server-side code:
Create a websocket.mjs file and write the following code:
import { WebSocketServer } from "ws";
const server = new WebSocketServer({ port: 3000 });
server.on("connection", (socket) => {
// send a message to the client
socket.send(JSON.stringify({
type: "hello from server",
content: [ 1, "2" ]
}));
// receive a message from the client
socket.on("message", (data) => {
const packet = JSON.parse(data);
switch (packet.type) {
case "hello from client":
console.log(packet.content)
// ...
break;
}
});
});
Run the server-side code:
node websocket.mjs
Step 3: Write the client code:
Create an index .html in the catalog
Write the following code:
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>HTML文档</title>
<meta name="keywords" content="">
<meta name="description" content="">
</head>
<body>
<script>
const socket = new WebSocket("ws://localhost:3000");
socket.addEventListener("open", () => {
// send a message to the server
socket.send(JSON.stringify({
type: "hello from client",
content: [ 3, "4" ]
}));
});
// receive a message from the server
socket.addEventListener("message", ({ data }) => {
const packet = JSON.parse(data);
switch (packet.type) {
case "hello from server":
console.log(packet.content)
// ...
break;
}
});
</script>
</body>
</html>
Open the index .html with a browser
Press F12 to view the console output.
Leave a Reply