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

时间:2014-10-23 16:08:08

标签: javascript node.js socket.io

我正在搜索是否有办法运行node.js&终端上的socket.io客户端。我的目标是客户和客户。服务器在终端上运行。它在网页上工作,但在终端没有任何想法吗?

3 个答案:

答案 0 :(得分:2)

从节点进程中简单地使用socket.io-client https://github.com/socketio/socket.io-client

答案 1 :(得分:1)

使用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');
});
<块引用>

服务器在 http://localhost:3000 上打开连接
接收来自客户端的消息并广播给其他客户端

客户:

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...')
    }); 
    
});
<块引用>

使用 rl.question() 从终端读取文本并使用 socket.emit() 将其发送到服务器
递归调用 send msg() 从终端读取文本并将其发送到服务器
socket.on() 用于接收来自其他客户端的消息

答案 2 :(得分:0)

您可以使用PhantomJS在终端上运行无头浏览器,并在加载到PhantomJS的页面中为socket.io客户端安装JavaScript。