4

websocket服务端与客户端代码示例

 1 year ago
source link: https://blog.p2hp.com/archives/10922
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

websocket服务端与客户端代码示例. ( json socket )

用到了ws库.

步骤:1安装ws

npm install ws

步骤2:服务端代码:

创建websocket.mjs文件,写入以下代码:

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;
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;
    }
  });
});

运行服务端代码:

node websocket.mjs

步骤3:编写客户端代码:

在目录中创建index.html

写入以下代码:

<!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>
<!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>

用浏览器打开index.html

按f12查看console输出即可.


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK