socket.io实现客户端和服务端的双向通信

时间:2023-01-04 22:14:25

首先创建项目文件夹并初始化,安装socket.io和express

npm init && npm i -S socket.io express

用express创建后端服务,创建index.js:

const express = require('express');
const http = require('http');
const fs = require('fs');
const path = require('path');
const socketIo = require('socket.io')

var app = express();
var server = http.Server(app);
var io = socketIo(server);

app.get('/', (req, res) => {
    var html = fs.readFileSync(path.resolve(__dirname, './index.html'), 'utf-8');
    res.send(html);
});



io.on('connection', socket => {
    socket.emit('hello', {
        message: 'message from server',
        time: (new Date()).toLocaleString()
    });
    socket.on('hi', res => {
        console.log(res);
    });
    // console.log('a user come ' + (new Date()).toLocaleString());
});

server.listen(3000, () => {
    console.log('server is listen on port 3000');
});

创建index.html,模拟客户端:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Document</title>
    <script src="/socket.io/socket.io.js"></script>
</head>
<body>
    <p>hello world</p>
    <script>
        var socket = io();
        socket.on('hello', res => {
            console.log(res);
        });
        socket.emit('hi', {
            message: 'message from client',
            time: (new Date()).toLocaleString()
        })
    </script>
</body>
</html>

项目文件夹:

socket.io实现客户端和服务端的双向通信

然后用node启动服务端:

node index.js

或者在package.json中写启动脚本

{
  "name": "chat",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1",
    "dev": "node index.js"
  },
  "author": "",
  "license": "ISC",
  "dependencies": {
    "express": "^4.16.3",
    "socket.io": "^2.1.1"
  }
}

然后执行

npm run dev

socket.io实现客户端和服务端的双向通信

成功启动后端服务,打开本地 localhost:3000 ,即可获取信息:

socket.io实现客户端和服务端的双向通信

socket.io实现客户端和服务端的双向通信