如何使用socket.io仅向我的房间发送消息?

时间:2020-03-16 17:27:44

标签: node.js sockets socket.io

我决定学习socket.io来创建一个扑克聊天游戏,您可以通过向机器人发出命令来进行游戏。

这就是我想要的: -用户进入网站 -用户想使用以下命令创建新游戏:!create -从这一刻起,用户只在新房间(作为通用ID创建)上写东西

这是现在的代码:

index.js(后端):

var app = require('express')();
var http = require('http').Server(app);
var io = require('socket.io')(http);
var port = process.env.PORT || 3000;

const games = new Map();
const generalRoom = 'generalRoom';

function Player() {

}

function Game(creator) {
  players = new Map();
  players.set(creator, Player());
}

function generate() {
  return (new Date()).getTime().toString(36)
}

app.get('/', function(req, res){
  res.sendFile(__dirname + '/index.html');
});

io.on('connection', function(socket){
  console.log(socket.id);
  socket.join(generalRoom);

  socket.on('chat message', function(msg){
    console.log('chat message: ' + msg);
    io.emit('chat message', msg);
  });

  socket.on('cmd', function(command){
    console.log('command ' + command + ' send by ' + socket.id);
    if(command === '!create') {
        const roomId = generate();
        games.set(roomId, new Game(socket.id));
        socket.emit('chat message', 'you sent this command ' + command);
        socket.emit('chat message', 'the id to pass to your friend is: ' + roomId);
        socket.emit('chat message', 'I will move you on the new room... ');
        socket.leaveAll();
        socket.join(roomId);
        socket.emit('chat message', 'can everyone read this?');
    }
  });
});

http.listen(port, function(){
  console.log('listening on *:' + port);
});

index.html(前端):

<!doctype html>
<html>
  <head>
    <title>Socket.IO chat</title>
    <style>
      * { margin: 0; padding: 0; box-sizing: border-box; }
      body { font: 13px Helvetica, Arial; }
      form { background: #000; padding: 3px; position: fixed; bottom: 0; width: 100%; }
      form input { border: 0; padding: 10px; width: 90%; margin-right: .5%; }
      form button { width: 9%; background: rgb(130, 224, 255); border: none; padding: 10px; }
      #messages { list-style-type: none; margin: 0; padding: 0; }
      #messages li { padding: 5px 10px; }
      #messages li:nth-child(odd) { background: #eee; }
      #messages { margin-bottom: 40px }
    </style>
  </head>
  <body>
    <div>
      <p>What you can do:</p>
      <ul>
        <li>send a normal message</li>
        <li>send a command, you need to put a ! in front of the command: 
          <ul>
            <li>
              <pre>!create</pre> allows you to create a new match. The bot will give a code to send to your friend
            </li>
            <li>
              <pre>!join $code</pre> allows you to join a match. Only the owner can start a match.
            </li>
          </ul> 
      </ul>
    </div>
    <ul id="messages"></ul>
    <form action="">
      <input id="m" autocomplete="off" /><button>Send</button>
    </form>
    <script src="https://cdn.socket.io/socket.io-1.2.0.js"></script>
    <script src="https://code.jquery.com/jquery-1.11.1.js"></script>
    <script>
      const generalRoom = 'generalRoom';
      $(function () {
        var socket = io();
        $('form').submit(function(){
          const message = $('#m').val();
          if (message.startsWith('!')) {
            socket.emit('cmd', message);
          } else {
            socket.emit('chat message', message);
          }
          $('#m').val('');
          return false;
        });
        socket.on('chat message', function(msg){
          $('#messages').append($('<li>').text(msg));
          window.scrollTo(0, document.body.scrollHeight);
        });
      });
    </script>
  </body>
</html>

根据我的理解,鉴于我是通过socket.join(room)加入后端的,所以我generalRoom上看不到任何其他消息,但我一直看到它们。

顺便说一句,socket.id总是打印一个新的ID,我认为一旦加入聊天,从客户端的角度来看,它总是相同的。

我在做什么错?

0 个答案:

没有答案