既然我们已经很熟悉Socket.IO了,让我们编写一个聊天应用程序,我们可以用它在不同的聊天室聊天。我们将允许用户选择用户名,并允许他们使用用户名聊天。首先,让我们设置我们的HTML文件来请求用户名

<!DOCTYPE html>
<html>
   <head>
      <title>Hello world</title>
   </head>
   <script src = "/socket.io/socket.io.js"></script>

   <script>
      var socket = io();
   </script>
   <body>
      <input type = "text" name = "name" value = "" placeholder = "Enter your name!">
      <button type = "button" name = "button">Let me chat!</button>
   </body>
</html>

现在,我们已经设置了请求用户名的HTML,让我们创建服务器来接受来自客户端的连接。我们将允许人们使用setUsername事件发送他们选择的用户名。如果用户存在,我们将通过userExists事件进行响应,否则将使用userSet事件。

var app = require('express')();
var http = require('http').Server(app);
var io = require('socket.io')(http);

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

users = [];
io.on('connection', function(socket) {
   console.log('A user connected');
   socket.on('setUsername', function(data) {
      if(users.indexOf(data) > -1) {
         users.push(data);
         socket.emit('userSet', {username: data});
      } else {
         socket.emit('userExists', data + ' username is taken! Try some other username.');
      }
   })
});

http.listen(3000, function() {
   console.log('listening on localhost:3000');
});

当人们点击按钮时,我们需要将用户名发送到服务器。如果用户存在,我们会显示一条错误消息;否则,我们会显示一个消息屏幕

<!DOCTYPE html>
<html>
   <head>
      <title>Hello world</title>
   </head>

   <script src = "/socket.io/socket.io.js"></script>
   <script>
      var socket = io();
      function setUsername() {
         socket.emit('setUsername', document.getElementById('name').value);
      };
      var user;
      socket.on('userExists', function(data) {
         document.getElementById('error-container').innerHTML = data;
      });
      socket.on('userSet', function(data) {
         user = data.username;
         document.body.innerHTML = '<input type = "text" id = "message">\
         <button type = "button" name = "button" onclick = "sendMessage()">Send</button>\
         <div id = "message-container"></div>';
      });
      function sendMessage() {
         var msg = document.getElementById('message').value;
         if(msg) {
            socket.emit('msg', {message: msg, user: user});
         }
      }
      socket.on('newmsg', function(data) {
         if(user) {
            document.getElementById('message-container').innerHTML += '<div><b>' +
               data.user + '</b>: ' + data.message + '</div>'
         }
      })
   </script>

   <body>
      <div id = "error-container"></div>
      <input id = "name" type = "text" name = "name" value = ""
         placeholder = "Enter your name!">
      <button type = "button" name = "button" onclick = "setUsername()">
         Let me chat!
      </button>
   </body>
</html>

现在,如果您使用相同的用户名连接两个客户端,将会出现如下图所示的错误

一旦您提供了一个可接受的用户名,您将被带到一个带有消息框和发送消息按钮的屏幕。现在,我们必须处理消息,并将消息定向到连接的客户端。为此,请修改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('index.html');
});

users = [];
io.on('connection', function(socket) {
   console.log('A user connected');
   socket.on('setUsername', function(data) {
      console.log(data);

      if(users.indexOf(data) > -1) {
         socket.emit('userExists', data + ' username is taken! Try some other username.');
      } else {
         users.push(data);
         socket.emit('userSet', {username: data});
      }
   });

   socket.on('msg', function(data) {
      //Send message to everyone
      io.sockets.emit('newmsg', data);
   })
});

http.listen(3000, function() {
   console.log('listening on localhost:3000');
});

现在,将任意数量的客户端连接到您的服务器,向它们提供用户名并开始聊天!在下面的例子中,我们连接了名为Ayush和Harshit的两个客户端,并从这两个客户端发送了一些消息