使用socket.io开发的在线聊天
发布于 9 年前 作者 tomoya92 5827 次浏览 最后一次编辑是 8 年前 来自 分享

下面是源码

//package.json
{
  "name": "chat",
  "version": "1.0.0",
  "description": "即时聊天",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "author": "",
  "license": "ISC",
  "dependencies": {
    "express": "^4.13.4",
    "lodash": "^4.12.0",
    "markdown-it": "^6.0.1",
    "socket.io": "^1.4.6"
  }
}
//index.js
var app = require('express')();
var http = require('http').Server(app);
var io = require('socket.io')(http);
var _ = require('lodash');
var MarkdownIt = require("markdown-it");
var md = new MarkdownIt({
  breaks: true,
  linkify: true
});

var users = [];

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

io.on('connection', function(socket) {

  socket.on('user connection', function(msg) {
    users.push({
      id: socket.id,
      name: msg
    })
    io.sockets.emit('hi', msg + '加入聊天室\n当前在线人数' + users.length);
  });

  socket.on('disconnect', function() {
    var i = _.findIndex(users, {
      id: socket.id
    });
    if (i >= 0) {
      var _user = users[i];
      _.remove(users, function(u) {
        return u.id == socket.id;
      })
      io.sockets.emit('hi', _user.name + '离开了聊天室\n当前在线人数' + users.length);
    }
  });

  socket.on('chat message', function(msg) {
    if (msg) {
      var i = _.findIndex(users, {
        id: socket.id
      });
      if (i >= 0) {
        io.emit('chat message', {
          user: users[i],
          msg: md.render(msg)
        });
      }
    }
  });

});

http.listen(4000, function() {
  console.log('listening on *:4000');
});
//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 textarea { border: 0; padding: 10px; width: 90%; margin-right: .5%; }
      .form button { width: 9%; background: rgb(130, 224, 255); border: none; padding: 17px; position: absolute; }
      #messages { list-style-type: none; margin: 0; padding: 0 0 60px 0; }
      #messages li { padding: 5px 10px; }
      #messages li:nth-child(odd) { background: #eee; }
    </style>
  </head>
  <body>
    <ul id="messages"></ul>
    <div class="form" style="display: none;">
      <textarea id="m" autocomplete="off" placeholder="支持markdown语法哦~~"></textarea><button id="send">发送</button>
    </div>

    <script src="/socket.io/socket.io.js"></script>
    <script src="http://code.jquery.com/jquery-1.11.1.js"></script>
    <script>
      $(function(){
        var name = prompt("输入昵称");
        console.log(name);
        if($.trim(name).length > 0) {
          var socket = io();
          socket.emit('user connection', name);
          $('#send').click(function(){
            socket.emit('chat message', $('#m').val());
            $('#m').val('');
            return false;
          });
          socket.on('chat message', function(msg){
            $('#messages').append('<li><p>'+msg.user.name+'说:</p><p>'+msg.msg+'</p></li>');
            $('html, body, #message').animate({scrollTop: $(document).height()}, 100);
          });
          socket.on('hi', function(msg){
            $('#messages').append($('<li style="text-align: center;">').text(msg));
          });
          $('.form').show();
        }
      })
    </script>
  </body>
</html>

启动:

npm install
node index.js

打开浏览器访问:http://localhost:4000 开源地址:https://github.com/liygheart/chedan 在线体验:http://chat.tomoya.cn/

9 回复

地址localhost 你太任性了 From Noder

不错,简单明了

@timor2015 本地调试嘛

来自酷炫的 CNodeMD

直接用index.html

   var socket = io("ws://chat.tomoya.cn");

这样也能聊

@yakczh 赞,学习了

回到顶部