- 這隻是的簡單的例子,通過網址參數控制自己的id,和私聊的對象
- http://localhost/ws.html?1:2 //我的id是1,我隻能給2發消息
- http://localhost/ws.html?1 //我的id是1,我一般不發,一發就是群發
- http://localhost/ws.html?:1 //我沒有id,我隻能接收群發資訊,我隻能給1發消息
- http://localhost/ws.html //專業群發
npm install ws --save
node.js端代碼
//這是運作在node.js上的
const WebSocket = require('ws');
const wss = new WebSocket.Server({
port:3030,
verifyClient: yan//驗證要不要給連接配接
})
function yan(info){
let url = info.req.url
// let i = url.search(6);
// if (i<0){
// console.log('拒絕連接配接');
// return false;
// }
console.log('通過連接配接' + url);
return true;
}
let user={};//存儲連接配接使用者
let online=0;//存儲線上人數
wss.on('connection',function(ws,req){
online =wss._server._connections;
console.log('目前線上' + online+'個連接配接');
ws.send('目前線上' + online+'個連接配接');
let i = req.url;//提取網址參數
let m = i.match(/(?<=\?)[^:]+?(?=:|$)/); //提取我是誰,這部分代碼隻有第一次連接配接的時候運作,如果後面連接配接的m值相同,前面的連接配接會被覆寫身份
if(m){
user[m] = ws;
};
let u = i.match(/(?<=:).+?$/); //提取發給誰
ws.on('message',function(msg){
console.log('收到'+i+'的消息:'+msg);
// ws.send(req.headers['sec-websocket-key'])
// ws.send(req.url)
if(u){
if (user[u]){
if (user[u].readyState===1){
user[u].send(msg);
ws.send('發送成功');
}else{
ws.send('對方掉線');
}
}else{
ws.send('找不到對象');
}
}else{//廣播
wss.clients.forEach(function each(client) {
if (client !== ws && client.readyState === WebSocket.OPEN) {
client.send(msg);
}
});
}
if (online != wss._server._connections){
online = wss._server._connections;
ws.send('目前線上' + online + '個連接配接');
}
// ws.send(req.headers.origin)
// ws.send(JSON.stringify(Array.from(wss.clients)))
// ws.send(JSON.stringify(ws))
// ws.send(JSON.stringify(req))
})
})
浏覽器端代碼
<!DOCTYPE html>
<html >
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
</head>
<body>
<div id="a"></div>
<input type="text" id="text"> <input type="button" value="發送" id="btn">
<hr>
<div id="b"></div>
<script>
let i=location.search;
// ?1:2 我是1,我要發給2
// ?1 我是1,要麼不發,一發就群發
// ?:2 别管我是誰,我要發給2
i=i.replace(/[^\d\?:]/g,'') //這條是去掉不是數字的,其實有字母也行的
let m=i.match(/(?<=\?)[^:]+?(?=:|$)/) //提取我是誰
let u=i.match(/(?<=:).+?$/) //提取發給誰
m=m?m+',':'誰?'
u=u? '我給' + u + '發資訊':'我群發'
a.innerHTML=('我是'+ m + u)
//-----------------------分割線----------------------------------------------
let ws =new WebSocket('ws://localhost:3030/'+i)
ws.onmessage=(evt)=>{
console.log(evt.data)
b.innerHTML += (evt.data+'<br>')
}
ws.onopen=()=>{
console.log('連接配接成功')
b.innerHTML += ('連接配接成功<br>')
// ws.send('你好')
}
ws.onerror=()=>{
console.log('連接配接錯誤')
b.innerHTML += ('連接配接錯誤<br>')
}
ws.onclose=()=>{
console.log('連接配接關閉')
b.innerHTML += ('連接配接關閉<br>')
}
//-----------------------分割線----------------------------------------------
btn.onclick=()=>ws.send(text.value? text.value:u)
</script>
</body>
</html>