简体   繁体   English

Socket.io简单节点应用程序无法正常工作

[英]Socket.io simple node app is not working

I have this little socket room app, but for a reason is not working. 我有这个小插座房间应用程序,但由于一个原因不起作用。 I'm trying to make the user join the room on click and display an alert, can't figure out the issue, I'm kinda new to sockets and can't even get this simple app working.. This is my code 我试图让用户加入房间点击并显示警告,无法弄清楚问题,我对套接字有点新,甚至无法让这个简单的应用程序工作..这是我的代码

////app.js ////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 ////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>

On the client side you have to: 在客户端,您必须:

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

On the server side: 在服务器端:

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?');
    });
});

You can not emit until you receive the connection. 在收到连接之前,您无法发出声音。

您应该实例化一个新的io实例,如下所示:

const socket = io();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM