套接字没有通信

时间:2016-09-29 02:52:16

标签: node.js sockets express socket.io

我正在尝试使用节点创建一个简单的应用程序并表达我可以与套接字共享实时数据的位置。无论我尝试什么,我都无法让服务器或客户端向对方发送消息。

服务器:

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

//set location for views
app.set('views', __dirname + '/views');
//set location for static files
app.use(express.static(path.join(__dirname, 'public')));
app.use('/scripts', express.static(__dirname + '/node_modules/'));

//create route 
app.get('/', function(req, res) {
  res.render('home.jade');
});

//Connection listener for io object
io.on('connection', function(socket){
    console.log('A user has connected');
    socket.on('test', function(data){
        console.log(data);
    });
})

server.listen(3000, "localhost");

客户:

var socket = io.connect('http://:localhost:3000');

$(document).on('click', '#submit-message', function() {
    socket.send('test', {contents: "hello"}); //static for now
});

1 个答案:

答案 0 :(得分:1)

现在它应该有用..

客户端:

var socket = io();

$(document).on('click', '#submit-message', function() {
    socket.emit('test', {contents: "hello"}); //static for now
});

问题是socket.send总是发出'message'事件,它就像socket.emit('message',{contents:“hello”})。如果您在客户端中使用socket.send,则必须使用socket.on('message',function(data){});在服务器中。