我有问题,因为这个例子不起作用,我不知道为什么......
服务器
var app = require('http').createServer(handler);
var io = require('socket.io').listen(app);
var fs = require('fs');
var port = 3250;
app.listen(port);
io.sockets.on('connection', function(socket) {
socket.on('room', function(room) {
socket.join(room);
});
var room = abc123
io.sockets.in(room).emit('m', 'what is going on, party people?');
});
客户端
var room = "abc123";
socket.on('connect', function() {
socket.emit('room', room);
});
socket.on('m', function(data) {
document.write(data);
});
我正在尝试这个https://gist.github.com/crabasa/2896891并且没有帮助:(
谢谢你的帮助!
答案 0 :(得分:3)
服务器:
var app = require('http').createServer(function(req,res){});
app.listen(3250);
var io = require('socket.io').listen(app)
//io = socketio.listen(server);
// handle incoming connections from clients
io.sockets.on('connection', function(socket) {
// once a client has connected, we expect to get a ping from them saying what room they want to join
socket.on('room', function(room) {
socket.join(room);
});
socket.on('say',function(data){
io.sockets.in(data.room).emit('message',data.message);
})
});
客户端:
<!DOCTYPE HTML>
<html>
<head>
<script src="http://192.168.1.7:3250/socket.io/socket.io.js"></script>
<script>
// set-up a connection between the client and the server
var socket = io.connect('http://192.168.1.7:3250');
// let's assume that the client page, once rendered, knows what room it wants to join
var room = "abc123";
socket.on('connect', function() {
// Connected, let's sign-up for to receive messages for this room
socket.emit('room', room);
});
socket.on('message', function(data) {
console.log('Incoming message:', data);
});
</script>
</head>
<body>
<button onclick='socket.emit("say",{"room":room,"message":"hello world"})'>Say hello world</button>
</body>
</html>
将192.168.1.7更改为您的IP地址,祝您好运!