套接字IO事件发出

时间:2018-07-21 17:19:05

标签: javascript node.js socket.io

我试图让客户端与服务器对话,但无法接收客户端发出的事件。每当有客户端连接时,就将连接建立为服务器console.logs connected to localhost:61201;但是,客户端不定期发出来自clientEvents的响应。

server.js

const port = 61201;
const ipAddress = "127.0.0.1"

var http = require('http');
var io = require('socket.io');
var server = http.createServer();
server.listen(port, ipAddress);
var socket = io.listen(server);

socket.on('connect', () => {
    console.log('connected to localhost:61201');
    socket.on('clientEvent', function (data) {
        console.log('message from the client:', data);
        socket.emit('serverEvent', "thanks server! for sending '" + data + "'");
    });
});

client.js

const port = 61201;
const ipAddress = "127.0.0.1";
const url = 'http://' + ipAddress + ':' + port;

var io = require('socket.io-client');

var socket = io(url);

socket.on('connect', () => {
    socket.on('serverEvent', function (data) {
        console.log('new message from the server:', data);
    });
    setInterval(function () {
        socket.emit('clientEvent', Math.random());
        console.log('message sent from the client');
    }, 3000);
});

1 个答案:

答案 0 :(得分:1)

您需要使用socket事件返回的connect对象。试试这个

socket.on('connect', (clientSocket) => {
    console.log('connected to localhost:61201');
    clientSocket.on('clientEvent', function (data) {
        console.log('message from the client:', data);
        clientSocket.emit('serverEvent', "thanks server! for sending '" + data + "'");
    });
});