我有这个小插座房间应用程序,但由于某种原因无法正常工作。我试图让用户通过点击加入房间并显示提醒,无法解决问题,我对套接字有点新意,甚至无法获得这个简单的应用工作..这是我的代码
//// app.js
var app = require('express')();
var http = require('http').Server(app);
var io = require('socket.io')(http);
app.get('/', function(req, res){
res.sendFile(__dirname + '/index.html');
});
io.on('connection', function(socket) {
socket.on('room', function(room) {
socket.join(room);
});
});
room = "abc123";
io.sockets.in(room).emit('message', 'what is going on, party people?');
http.listen(3000, function(){
console.log('listening on localhost:3000');
});
////的index.html
<!DOCTYPE html>
<html>
<head>
<title>flip</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<script src="https://cdn.socket.io/socket.io-1.4.5.js"></script>
<link rel="stylesheet" type="text/css" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
</head>
<body>
<button>Join the room!</button>
</body>
<script>
var socket = io.connect();
// let's assume that the client page, once rendered, knows what room it wants to join
var room = "abc123";
socket.on('connect', function() {
$('button').click(function() {
socket.emit('room', room);
})
});
socket.on('message', function(data) {
alert(data)
});
</script>
</html>
答案 0 :(得分:3)
在客户端,你必须:
var socket = io.connect('http://localhost:3000');
在服务器端:
io.on('connection', function(socket) {
socket.on('room', function(room) {
socket.join(room);
room = "abc123";
io.to(room).emit('message', 'what is going on, party people?');
});
});
在收到连接之前,您无法发出声音。
答案 1 :(得分:0)
您应该实例化io
的新实例,如下所示:
const socket = io();