4

この例が機能せず、理由がわからないため、問題があります...

サーバ

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を試していますが、役に立ちませんでした:(

ご協力ありがとう御座います!

4

1 に答える 1

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 アドレスに変更してください。頑張ってください!

于 2013-07-17T11:35:18.250 に答える