var express = require('express');
var app = require('express')();
var http = require('http').Server(app);
var io = require('socket.io')(http);
http.listen(3000, function(){
console.log('listening on *:3000');
});
app.use('/js',express.static(__dirname+'/js'));
app.get('/', function(req, res){
res.sendfile('codeschool_chattr.html');
});
io.on('connection', function(client){
console.log('a user connected');
var nick="";
client.on('join',function(name){
client.nickname=name;
});
client.on('disconnect', function(){
console.log('user disconnected');
});
client.on('chat message', function(msg){
client.broadcast.emit('chat message', msg);
});
});
我有一个套接字io应用程序代码,这里聊天消息被发送到除了发送它的人之外的所有连接的客户端,我应该做什么或者我错过了什么来实现这一点。 这里也是我的前端剧本 -
<script src="/socket.io/socket.io.js"></script>
<script>
var server = io.connect('http://localhost:3000');
server.on('connect',function(data){
var nick = prompt(" What do your friends call you? ");
server.emit('join',nick);
});
$('form').submit(function(){
server.emit('chat message', $('#m').val());
$('#m').val('');
return false;
});
server.on('chat message', function(msg){
$('#messages').append($('<li>').text(msg));
});
</script>
答案 0 :(得分:1)
尝试
client.on('chat message', function(msg){
io.sockets.emit('chat message', msg);
});
这应该发送给所有连接的客户端。