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