本文主要是使用的心得,參考的網(wǎng)址是websocket,本例中使用的是Websocket-Node 服務(wù)器模式,本地全局安裝node即可
服務(wù)端文件,本文命名為socketserver.js ,代碼如下:
var WebSocketServer = require('websocket').server;
var http = require('http');
var server = http.createServer(function(request, response) {
console.log((new Date()) + ' Received request for ' + request.url);
response.writeHead(404);
response.end();
});
server.listen(8080, function() {
console.log((new Date()) + ' Server is listening on port 8080');
});
wsServer = new WebSocketServer({
httpServer: server,
autoAcceptConnections: false
});
function originIsAllowed(origin) {
return true;
}
wsServer.on('request', function(request) {
if (!originIsAllowed(request.origin)) {
request.reject();
console.log((new Date()) + ' Connection from origin ' + request.origin + ' rejected.');
return;
}
var connection = request.accept('echo-protocol', request.origin);
console.log((new Date()) + ' Connection accepted.');
connection.on('message', function(message) {
if (message.type === 'utf8') {
console.log('Received Message: ' + message.utf8Data);
connection.sendUTF(message.utf8Data);
}
else if (message.type === 'binary') {
console.log('Received Binary Message of ' + message.binaryData.length + ' bytes');
connection.sendBytes(message.binaryData);
}
});
connection.on('close', function(reasonCode, description) {
console.log((new Date()) + ' Peer ' + connection.remoteAddress + ' disconnected.');
});
});
然后編寫客戶端文件index.html
<!DOCTYPE html>
<html lang="en">
<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>webSocket學(xué)習(xí)</title>
<script>
var client = new WebSocket('ws://localhost:8080/', 'echo-protocol');
client.onerror = function() {
console.log('Connection Error');
};
client.onopen = function() {
console.log('WebSocket Client Connected');
var contentd = document.getElementById('content');
const p = document.createElement('p');
p.innerHTML = `帥哥已上線`;
contentd.appendChild(p);
};
client.onclose = function() {
console.log('echo-protocol Client Closed');
};
client.onmessage = function(e) {
var contentd = document.getElementById('content');
if (typeof e.data === 'string') {
const newDate =JSON.parse(e.data)
const p = document.createElement('p');
p.innerHTML = newDate.user + "說:" +newDate.sendVal
contentd.appendChild(p)
}
};
function send(){
var User = document.getElementById('User').value;
var sendVal = document.getElementById('sendVal').value;
const data = {
"user":User,
'sendVal':sendVal
}
sendVal && User ?function(){client.send(JSON.stringify(data));document.getElementById('sendVal').value='';}():alert("所有數(shù)據(jù)都不能為空")
}
</script>
</head>
<body>
<label for="User">用戶名:</label> <input type="text" id="User"><br>
<label for="sendVal">消息 :</label> <input type="text" id="sendVal">
<button onclick="send()">發(fā)送</button>
<div id="content">
</div>
</body>
</html>
編寫完成以后,保存兩個文件,在文件所在目錄下打開控制臺輸入
node socketserver.js
在網(wǎng)頁上就能進行嘗試了,如圖

image.png
點擊發(fā)送:

image.png
本次嘗試的直是單頁面的,下次嘗試多頁面的通信,做成一個仿聊天室的再見。如有不對,歡迎指正