我正在寻找是否有办法在终端上运行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 usingsocket.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/