使用socket.io开发简单群聊功能

1、新建package.json文件:

{
  "name": "socket-chat-example",
  "version": "0.0.1",
  "description": "my first chat socket-chat-example",
  "dependencies": {
    "express": "^4.14.0",
    "socket.io": "^1.4.8"
  }
}

2、新建index.js用于聊天服务:

//使用express搭建web服务器
var express = require("express");
var app = express();
var http = require("http").Server(app);
//使用socket.io监听事件
var io = require("socket.io")(http);
//使用express发送css js等静态资源
app.use(express.static("public"));

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

//socket.io监听事件
io.on("connection",function(socket){
    console.log("a user connected");
    socket.on("disconnect",function(){
        console.log("a user disconnected");
    });

    //实时监听chat message事件
    socket.on("chat message",function(msg){
        io.emit("chat message",msg);
    })
});

//服务器监听开启
http.listen(3000,function(){
    console.log("listening on *:3000");
});

3、聊天页面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; }
    </style>
  </head>
  <body>
    <ul id="messages"></ul>
    <form action="">
      <input id="m" autocomplete="off" /><button>Send</button>
    </form>
    <script src="https://cdn.socket.io/socket.io-1.4.5.js"></script>
    <script src="http://libs.baidu.com/jquery/1.11.3/jquery.min.js"></script>
    
    <script type="text/javascript">
        var socket = io();
        $('form').submit(function(){
               //点击发送按钮,提交输入的信息
            socket.emit('chat message', $('#m').val());
            $('#m').val('');
            return false;
          });
        
          socket.on('chat message', function(msg){
            //将chat message显示在页面
            $('#messages').append($('<li>').text(msg));
          });
    </script>
  </body>
</html>

具体参考:http://socket.io/

原文地址:https://www.cnblogs.com/vipzhou/p/5787823.html