Node socket.io docker

server

bash 复制代码
npm install express
bash 复制代码
npm install socket.io
javascript 复制代码
const express = require('express');
const http = require('http');
const socketIO = require('socket.io');

const app = express();
const server = http.createServer(app);
const io = socketIO(server);

io.on('connection', (socket) => {
    console.log('User connected');

    socket.on('chat message', (msg) => {
        console.log('message: ' + msg);
        io.emit('chat message', msg); // to all
    });

    socket.on('disconnect', () => {
        console.log('User disconnected');
    });
});

server.listen(24525, () => {
    console.log('Node Server is running on port 24525');
});

docker

dockerfile

bash 复制代码
FROM node:16-alpine

WORKDIR /usr/src/app

COPY package*.json ./
RUN npm ci --only=production

COPY . .

EXPOSE 24525

CMD ["node", "skio.js"]
bash 复制代码
docker build -t nodeskio .

docker run -p 24525:24525 -d nodeskio

##login push

#docker login
#docker push your-image-name

client

bash 复制代码
npm install socket.io-client
javascript 复制代码
const io = require('socket.io-client');
const readline = require('readline');
const rl = readline.createInterface({
    input: process.stdin,
    output: process.stdout
});

const socket = io.connect('http://localhost:24525');

socket.on('connect', () => {
    console.log('Connected to server');
});

// 监听从服务器接收到的消息
socket.on('chat message', (msg) => {
    console.log('Message from server:', msg);
});

// 处理用户输入并发送到服务器
rl.on('line', (input) => {
    if (input.toLowerCase() === 'exit') {
        console.log('Exiting...');
        rl.close();
        process.exit(0);
    } else {
        socket.emit('chat message', input);
    }
});

// 处理关闭事件
rl.on('close', () => {
    socket.disconnect();
    console.log('Connection closed.');
});
bash 复制代码
npm run 
相关推荐
ADFVBM3 小时前
【Node.js]
node.js
摆烂式编程3 小时前
node.js 07.npm下包慢的问题与nrm的使用
前端·npm·node.js
东锋1.34 小时前
npm命令与yarn命令的区别
前端·npm·node.js
一纸忘忧9 小时前
Bun 1.2 版本重磅更新,带来全方位升级体验
前端·javascript·node.js
Amy_cx13 小时前
npm install安装缓慢或卡住不动
前端·npm·node.js
m0_748229991 天前
从零到上线:Node.js 项目的完整部署流程(包含 Docker 和 CICD)
docker·容器·node.js
yqcoder1 天前
node.js 文件操作
node.js
木偶☜1 天前
Node.js接收文件分片数据并进行合并处理
服务器·javascript·arcgis·node.js
梦魇梦狸º1 天前
node安装与管理
macos·node.js