nodejs+socket.io即时聊天实例

在这之前你应该先安装好 Node.js,安装过程不再讲解

首先在你的电脑上创建一个新目录,姑且命名为 chat,然后在该目录创建两个文件,分别是 app.js 和 index.html。

app.js

var fs = require('fs')
    , http = require('http')
    , socketio = require('socket.io');
 
var server = http.createServer(function(req, res) {
    res.writeHead(200, { 'Content-type': 'text/html'});
    res.end(fs.readFileSync(__dirname + '/index.html'));
}).listen(8080, function() {
    console.log('Listening at: http://localhost:8080');
});
 
socketio.listen(server).on('connection', function (socket) {
    socket.on('message', function (msg) {
        console.log('Message Received: ', msg);
        socket.broadcast.emit('message', msg);
    });
});

安装 Socket.IO 了,可在命令行窗口进入当前文件目录中执行如下命令

npm install socket.io

运行  app.js  服务

node app.js

现在你可以打开两个浏览器,访问 http://127.0.0.1:8080/ 地址开始互聊了



原文地址:https://www.cnblogs.com/jiangu66/p/3243973.html