基於Node.js + Web Socket 簡易聊天室

來源:互聯網
上載者:User

標籤:read   href   image   query   20px   else   idt   sockets   eve   

本文案例環境為mac系統,你需要先安裝nodejs,方法比較簡單,直接去nodejs官網下載即可。

環境:

mime

首先通過npm進行安裝

  • 在我們的專案檔夾下開啟命令列(tip: 按住Shift同時右擊,可以在右鍵菜單中找到‘從此處開啟命令列‘選項)
  • 在命令列中輸入 npm install mime --save 斷行符號進行安裝
  • 然後在chat.js中通過require(‘mime‘)將其引入到項目中進行使用

mime是node.js中管理路由響應請求的模組,根據請求的URL返回相應的HTML頁面

 

socket.io

Node.js中使用socket的一個包。使用它可以很方便地建立伺服器到用戶端的sockets串連,發送事件與接收特定事件。

同樣通過npm進行安裝 npm install socket.io --save 。安裝後在node_modules檔案夾下新產生了一個socket.io檔案夾,其中我們可以找到一個socket.io.js檔案。將它引入到HTML頁面,這樣我們就可以在前端使用socket.io與伺服器進行通訊了。

 

註:在瀏覽器中用本地localhost開啟

以下是代碼,主要是htlm部分  css部分  js部分

html文檔以及處理用戶端部分js

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>h9聊天室-beta版</title>
<link rel="stylesheet" href="../css/index.css">
</head>
<body>
<div class="chat">
<h2>歡迎來到h5大世界 當前線上人數<span>0</span></h2>
<ul>

</ul>
</div>
<form>
<input type="text" class="message">
<input type="button" value="發送" class="btn"/>
</form>

</body>
<script src="../socket.io/socket.io.js"></script>
<script>
var socket=io(‘http://10.80.16.238:3000‘);
var span=document.querySelector(‘span‘);
var btn=document.querySelector(‘.btn‘);
var list=document.querySelector(‘ul‘);
var info=document.querySelector(‘.message‘);
btn.onclick=function(ev){
ev.preventDefault();
var message=info.value;
socket.emit(‘message‘,{info:message});
}
socket.on(‘news‘,function(data){
var num=data.num;
var say=data.say;
var li=document.createElement(‘li‘);
li.innerHTML=say;
list.appendChild(li);
span.innerHTML=num;
})
</script>
</html>


CSS部分:
body{
margin: 0 auto;
background-color:lightgray;
}
.chat{
width:800px;
min-height:400px;
background-color:lightblue;
margin: 0 auto;
}

.chat h2{
height:40px;
line-height: 40px;
background-color:gold;
font-size: 20px;
text-align: center;
}
ul{
list-style-type:none;
margin: 0;
padding: 0;
}
li{
height:30px;
line-height: 30px;
font-size: 20px;
}
form{
width:800px;
margin:50px auto;
}
.message{
width:600px;
height:60px;
font-size:20px;
}
.btn{
width:100px;
height:30px;
background-color: aqua;
font-size:20px;
}


服務端js: chat.js檔案

var http=require(‘http‘);
//建立伺服器
var server=http.createServer(handle);
var fs=require(‘fs‘);

var mime=require(‘mime‘);

//綁定伺服器
var io=require(‘socket.io‘)(server);

function handle(req,res){
console.log(req.url)
var filePath=‘‘;
if (req.url=="/"){
filePath="./html/index.html"
}else{
filePath="."+req.url
}
Static(res,filePath)
}
function Static(res,filePath){
fs.exists(filePath,function(exist){
if (exist){
fs.readFile(filePath,function(err,data){
if(err){
send404(res)
}

res.writeHead(200,{
‘Content-Type‘:mime.lookup(filePath)
})
res.end(data)
})
}else{
send404(res)
}
})
}
server.listen(3000,function(){
console.log(‘go go go‘)
});


function send404(res){
res.writeHead(404,{
‘Content-Type‘:‘text/plain‘
})
res.end(‘404, sorry not found‘)
}

//發送,接收資訊
var num=1;
io.on(‘connection‘,function(socket){
num++;
// on 事件名,接受回調
// 服務端要和用戶端一一對應
socket.on(‘message‘,function(data){
console.log(data.info);
// emit 事件名,{發射主體}
io.sockets.emit(‘news‘,{name:‘wj‘,num:num,say:data.info});
})
})


 

基於Node.js + Web Socket 簡易聊天室

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.