使用Socket.io广播消息时出现问题

时间:2018-07-16 04:25:35

标签: javascript jquery node.js websocket socket.io

每当用户开始输入内容时,我都试图输出“ XYZ正在输入内容”的消息,但我似乎无法修复我的代码。我觉得我的代码的App.JS中的'socket.broadcast.emit'似乎是问题,但我不确定。如果可能的话,有人可以指出正确的方向来帮助我修复我的聊天应用。预先感谢!

Index.HTML

<!doctype html>
 <html>
 <head>
  <title>Chit Chat</title>
  <link rel="stylesheet" href="/css/styles.css">
 </head>
  <body>

   <ul id="messages"></ul>
   <div id="typing"></div>

   <form action="">
    <input id="username" placeholder="Username" type="text" />
    <input id="message-box" autocomplete="off" type="text" placeholder="Type Message" />
    <button id="button">Send</button>
   </form>


 <script src="/socket.io/socket.io.js"></script>
 <script src="https://code.jquery.com/jquery-3.3.1.min.js"></script>
 <script src="/js/scripts.js" charset="utf-8"></script>
 </body>
</html>

App.JS(服务器)

var express = require('express');
var app = require('express')();
var bodyParser = require('body-parser');
var http = require('http').Server(app);
var io = require('socket.io')(http);

app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: true}))
app.use(express.static('./public'));

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

var port = process.env.PORT || 3000;

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

// Socket.io
io.on('connection', function(socket) {
 // when the client emits 'new message', this listens and executes
 socket.on('new message', function(data) {
  // we tell the client to execute 'new message'
  io.sockets.emit('new message', data);
 });
// when the client emits 'typing', we broadcast it to others
 socket.on('typing', function(data){
  socket.broadcast.emit('typing', data);
 });
});

Scripts.JS

console.log('Loaded');
var socket = io();

$(function (){
 chat();
 emitEvents();
 isTyping();
});

function chat() {
 $('form').submit(function(e){
  var message = {
  username: $('#username').val(),
  message: $('#message-box').val()
  }
  e.preventDefault();
  socket.emit('new message', message);
   $('#message-box').val('');
  });
}

function isTyping() {
 $('#message-box').keypress(function() {
  socket.emit('typing', $('#username').val());
 });
}

function emitEvents() {
 socket.on('typing', function(data){
  console.log(data);
  $('#typing').append($('<p>').text(data + 'is typing'));
 });
 socket.on('new message', function(data){
  $('#messages').append($('<li>').text(data.username + ': ' + 
  data.message));
 });
}

1 个答案:

答案 0 :(得分:1)

我尝试了您的代码,它正在工作。我创建了一个live example

我在scripts.js中进行了2次修改,因此在键入过程中,键入消息只会出现一次。

function emitEvents() {
    socket.on('typing', function(data){
        console.log(data);
        $('#typing').html($('<p>').text(data + ' is typing')); // update
    });
    socket.on('new message', function(data){
        $('#typing').html($('<p>').text('')); // update
        $('#messages').append($('<li>').text(data.username + ': ' + data.message));
    });
}

代码socket.broadcast.emit意味着发送给除发件人以外的所有客户端。

签出Socket.IO cheatsheet