在我們正式開始前,各位小伙伴請允許我先叨叨下。最近認(rèn)為做一個神神叨叨的程序員要比高冷的程序員可愛一些,所以在抖腿背景音樂,我搖著頭抖著腿敲下這篇文,說起來最近愛上抖腿電音是源于最近愛上B站鬼畜區(qū)了。好啦不廢話啦,太叨叨也是惹人嫌的,畢竟我還是想做一個可愛的孩子。
因為我已經(jīng)npm 好了express所以沒有npm express的小伙伴們可以先
npm install express --save
若果你不想npm express 也可以,原生的node http 請求的服務(wù)端代碼下面也會貼出,然后是
npm install ws --save
以下是express下的websocket
客戶端代碼(想要更清楚的了解websocket和其api的小伙伴們可以去看看阮一峰大神的websocket教程或者百度,相關(guān)教程代碼很多的,因為我也是新手來著所以這里我就只實現(xiàn)了一些功能)
功能代碼部分
<script>
var ws = new WebSocket('ws://localhost:3000');
// 新建一個WebSocket通信,連接一個端口號為3000的本地服務(wù)器
ws.onopen = function (e) { //連接建立時觸發(fā)函數(shù)
console.log('Connection to server opened'+ws.readyState);
$('#show').html("連接狀態(tài):"+ws.readyState+"</br>")
// 只讀屬性readyState表示連接狀態(tài)
}
ws.onmessage=function (evt) { //客戶端接收服務(wù)端數(shù)據(jù)時觸發(fā)
$("#show").append(evt.data + "</br>");
//向頁面追加顯示服務(wù)端發(fā)送給客戶端的消息
}
ws.onclose = function(evt) { //連接關(guān)閉時觸發(fā)
console.log("WebSocketClosed!");
console.log(evt);
};
function sendMessage() { //向服務(wù)端發(fā)送消息
var msg=$('#message').val();
var s={msg:msg};
ws.send(JSON.stringify(s)); //傳送字符串化的json對象
chang();
}
function chang() { //實屬無聊改變輸入框的內(nèi)容
$('#message').val("");
}
function exit() {
ws.close(); //關(guān)閉ws通信
console.log("退出啦");
}
</script>
服務(wù)端代碼(app.js)
var http = require('http');
var url=require('url');
var WebSocket=require('ws');
var server = http.createServer(app);
var wss=new WebSocket.Server({ server:server });
wss.broadcast=function broadcast() { //服務(wù)端廣播消息
wss.clients.forEach(function each (client) {
if(client.readyState==WebSocket.OPEN){
client.send("開始通信吧!");
}
})
}
wss.on('connection',function connection(ws,req) {
var s;
ws.on('message',function incoming(message) {
console.log(message);
var smg = JSON.parse(message);
// 把傳過來的字符串又json化了,別問我為什么這么無聊
console.log(smg.msg + " " + smg.name);
if(smg.msg!="") {
s = smg.name + "說:" + smg.msg;
ws.send(s);
}else {
ws.send("說些什么吧,別這么高冷呀")
}
});
wss.broadcast();
})
ok以后運行express啟動文件就可以啦
下面是運行截圖
服務(wù)端廣播消息

客戶端發(fā)送消息
控制臺消息
到此一個簡單express下的websocket通信就完成了
下面是原生部分
服務(wù)端代碼
const http=require('http');
const url=require('url');
const fs=require('fs');
var WebSocket=require('ws');
var fun=function (request,response) {
var stream=fs.createReadStream('../views/ws.html',{flag:'r',encoding:'utf8'});
stream.pipe(response);
}
var server =http.createServer(fun).listen(8000);
var wss=new WebSocket.Server({ server:server });
wss.broadcast=function broadcast() {
wss.clients.forEach(function each (client) {
if(client.readyState==WebSocket.OPEN){
client.send("開始通信吧!");
}
})
}
wss.on('connection',function connection(ws,req) {
var s;
//const location = url.parse(req.url, true);
ws.on('message',function incoming(message) {
console.log(message);
var smg = JSON.parse(message);
console.log(smg.msg + " " + smg.name);
if(smg.msg!="") {
s = smg.name + "說:" + smg.msg;
ws.send(s);
}else {
ws.send("說些什么吧,別這么高冷呀")
}
});
wss.broadcast();
})
ws.html的內(nèi)容
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<script language="JavaScript" src="http://code.jquery.com/jquery-1.11.0.js"></script>
</head>
<body>
<div id="show"></div>
<div >
<input id="message" type="text" style="width: 200px">
<button type="button" id="send"
onclick="sendMessage();">
Send!
</button>
<button type="button" id="send"
onclick="exit();">
exit
</button>
</div>
<script>
var ws = new WebSocket('ws://localhost:8000');
ws.onopen = function (e) {
console.log('Connection to server opened'+ws.readyState);
$('#show').html("連接狀態(tài):"+ws.readyState+"</br>")
}
ws.onmessage=function (evt) {
$("#show").append(evt.data + "</br>");
}
ws.onclose = function(evt) {
console.log("WebSocketClosed!");
console.log(evt);
};
function sendMessage() {
var msg=$('#message').val();
var s={msg:msg,name:"山上的大王"};
ws.send(JSON.stringify(s));
chang();
}
function chang() {
$('#message').val("");
}
function exit() {
ws.close();
console.log("退出啦");
}
</script>
</body>
</html>
因為沒有寫靜態(tài)資源請求部分的代碼所以界面略丑,大家將就著看吧。
原生截圖