【www.bbyears.com--js教程】
注:部分引用es6的写法,聊天室很简单,就是创建room,更改名称,简单聊天等功能!
命令:
/nick 用户名 //修改用户名
/join 房间名 //修改房间名称
入口文件server.js
const http = require("http");
const fs = require("fs");
const path=require("path");
const mime=require("mime");
var cache ={};
const hostname = "127.0.0.1";
const port = 3000;
var send404=(response)=>{
response.writeHead(404,{"Content-Type":"text/plain"});
response.write("error:404");
response.end()
}
var sendFile=(response,filePath,fileContents)=>{
response.writeHead(200,{"Content-Type":mime.lookup(path.basename(filePath))});
response.end(fileContents)
}
var serveStatic=(response,cache,absPath)=>{
if(cache[absPath]){
sendFile(response,absPath,cache[absPath]);
}else{
fs.exists(absPath,(exists)=>{
if(exists){
fs.readFile(absPath,(err,data)=>{
if(err){
send404(response);
}else{
cache[absPath]=data;
sendFile(response,absPath,data)
}
})
}else{
send404(response);
}
})
}
}
var server = http.createServer((req,res) =>{
var filePath =false;
if(req.url=="/"){
filePath="public/index.html"
}else{
filePath="public"+req.url
}
var absPath="./"+filePath;
serveStatic(res,cache,absPath)
});
server.listen(port,hostname,()=>{
console.log(`hello,welcome to nodejs,you are already at http://${hostname}:${port}/`)
});
var chatServer =require("./lib/chat_server");
chatServer.listen(server);
app.js演示本地创建本地https服务器。
var https = require("https")
const fs = require("fs")
const hostname = "127.0.0.1"
const port = 3000
const options ={
key:fs.readFileSync("./key.pem"),
cert:fs.readFileSync("./key-cert.pem")
}
const server = https.createServer(options,(req, res) => {
res.statusCode = 200
res.setHeader("Content-Type", "text/plain")
res.end("Hello World\n")
})
server.listen(port, hostname, () => {
console.log(`Server running at https://${hostname}:${port}/`)
})
创建本地https服务器私钥key.pem命令
openssl genrsa 1024 > key.pem命令
除了私钥还要用证书,创建本地证书命令:
openssl req -x509 -new -key key.pem > key-cert.pem
基本的代码如下
var https = require("https")
const fs = require("fs")
const hostname = "127.0.0.1"
const port = 3000
const options ={
key:fs.readFileSync("./key.pem"),
cert:fs.readFileSync("./key-cert.pem")
}
const server = https.createServer(options,(req, res) => {
res.statusCode = 200
res.setHeader("Content-Type", "text/plain")
res.end("Hello World\n")
})
server.listen(port, hostname, () => {
console.log(`Server running at https://${hostname}:${port}/`)
})
因为我们的证书不是有证书颁发机构颁发的,所有会有安全提示。假如要在服务器上面用https的,那么要去找个证书的颁发机构(CA)进行注册,并为你的服务器取得一份真实的、受信任的证书!