javascript - 在终端上运行客户端socket.io

标签 javascript node.js socket.io

我正在寻找是否有办法在终端上运行node.js 和socket.io 客户端。我的目标是客户端和服务器都在终端上运行。它可以在网页中运行,但不能在终端中运行,有什么想法吗?

最佳答案

使用 socket.io 和 readline 的基于终端的聊天应用程序

服务器:

var app = require('express')();
var http = require('http').createServer(app);
var io = require('socket.io')(http);

io.on('connection', (socket) => {
    console.log('a user connected');
    
    socket.on('disconnect', () => {
        console.log('user disconnected');
    });
    
    let eventName = 'simple chat message';
    
    let broadcast = (msg) => socket.broadcast.emit(eventName, msg);
    
    socket.on(eventName, (msg, ackFn) => {
        console.log('message: ' + msg);
        // broadcast to other clients after 1.5 seconds
        setTimeout(broadcast, 1500, msg);
    });
});

http.listen(3000, () => {
    console.log('listening on *:3000');
});

Server opens connection on http://localhost:3000
Receive messages from client and broadcast to other client

客户:

const io = require("socket.io-client");
const readline = require('readline');
const rl = readline.createInterface({ input: process.stdin,  output: process.stdout });

rl.question('What\'s your name ? ', (name) => {
    const socket = io('http://localhost:3000');

    const sendMsg = () => {
        rl.question('> ', (reply) => {
            console.log(`Sending message: ${reply}`);
            socket.emit('simple chat message', `${name} says ${reply}`);
            sendMsg();
        });
    }

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

    socket.on('simple chat message', (message) => {
        console.log(message);
    });

    socket.on('disconnect', () => {
        console.log('Connection lost...')
    }); 
    
});

Read text from terminal using rl.question()and send it to server using socket.emit()
send msg() is called recursively to read text from terminal and send it to server
socket.on() is used to receive messages from other clients

关于javascript - 在终端上运行客户端socket.io,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26532428/

相关文章:

javascript - ES6 使用 --experimental-modules 在 Node 中导入

javascript - 如何知道何时使用 socket.io 订阅/取消订阅 channel

node.js - 套接字.io : associate browser and computer with the connection

javascript - 动画 SVG : Move shape in direction of mouse/rotate around fixed point?

javascript - 我无法在 ExpressJS 中使用静态 JS 文件

javascript - 如何使用 jquery 激活 'nav-link disabled'?

javascript - Browserify/JavaScript,otherjs.myfunction 不是 function()

node.js - 登录heroku上的express服务器

javascript - 在 URL 中实现 JavaScript 和文本

node.js - 在 Node.js 中,如何使父对象发出子对象的所有事件?