返回 原生NodeJ...... 登陆

原生NodeJs制作一个简易聊天室

阿神 2016-11-07 15:47:03 499

准备工作

安装NodeJs环境

安装编译器Sublime

如果网速不理想,可以百度一下如何加快npm的速度~

使用node搭建一个简单的网站后台

做完准备工作之后,新建文件夹chatroom,在chatroom中打开cmd,在控制台输出npm init。进行设置,得到package.json文件

{
  "name": "chatroom",
  "version": "1.0.0",
  "description": "multiroom chat server",
  "main": "app.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "keywords": [
    "chatroom"
  ],
  "author": "yyg",
  "license": "ISC",
}

安装socket.io以及mime。执行如下代码:

npm install socket.io --save-dev
npm install mime --save-dev

这里 mime 模块是用于获取所发送文件的类型。使用mime来获取文件类型来设置HTTP头的Content-Type。而 socket.io 则是这个聊天室的主角了,这是一个支持事实通讯而设计的轻量的双向通信协议。

var http = require('http');
var fs = require('fs');
var path = require('path');
var mime = require('mime');
var socketio = require('socket.io');
function send404 (res) {
    res.writeHead(404, {'ContentType': 'text/plain'});
    res.write('you are in a black hole');
    res.end();
}
function sendFile (res, filePath, fileContent) {
    res.writeHead({
        200,
        'ContentType': mime.lookup(path.basename(filePath))
    });
    res.end(fileContents);
}

200代表返回成功。

var cache = {};
function serveStaticFile (res, cache, absPath) {
    if(cache[absPath]) { //检测是否文件已经存在于内存,如果存在直接返回。
        sendFile(res, absPath, cache[absPath]);
    } else {
        fs.exists(absPath, function(exists){ //检测absPath路径下有没有此文件
            if(exists) {
                fs.readFile(absPath, function(err, data){
                    if(err) {
                        send404(res);
                    } else {
                        cache[absPath] = data; //存进内存
                        sendFile(res, absPath, data);
                    }
                });
            } else {
                send404(res);
            }
        });
    }
}
var server = http.createClient(function(req, res) {
    var filePath = false;
    if(req.url == '/') {
        filePath = 'public/index.html';
    } else {
        filePath = 'public/' + req.url;
    }
    var absPath = './' + filePath;
    serveStaticFile(res, cache, absPath);
});
server.listen(3000, function(req, res) {
    console.log('server started at port 3000');
});

敲完代码,大功告成!接下来再chatroom中新建文件夹public保存静态文件,建立一个主页index,内容随便填写。在命令行中输入node app,在浏览器中打开localhost:3000看看效果吧~

最新手记推荐

• 用composer安装thinkphp框架的步骤 • 省市区接口说明 • 用thinkphp,后台新增栏目 • 管理员添加编辑删除 • 管理员添加编辑删除

全部回复(0)我要回复

暂无评论~
  • 取消 回复 发送
  • PHP中文网