A small Demo simulates real-time communication, which is mainly realized by socket.io framework (further encapsulation of websocket)
1. Environmental preparation:
1) Node.js environment – > download and install on the official website
2) socket.io.js file https://cdnjs.com/libraries/socket.io
3) Install the module according to the instructions of the official website
npm install socket.io
4) Writing html and js files
The page is very simple, click the button to send the content of the input box to the server, and the received information will be displayed below (different status information and different color identification)
<html>
<head>
<meta charset="utf-8"/>
<title>WebSocket</title>
<script src="socket.io.js"></script>
</head>
<body>
<input type="text" id="sendText">
<button id="sendBtn">Send out</button>
<div id="recvText"></div>
<script type="text/javascript">
//Establish connection
var socket = io("ws://localhost:3000/");
//send message
document.getElementById("sendBtn").onclick = function(){
var sendMsg = document.getElementById("sendText").value;
socket.emit('client', sendMsg);
}
//receive messages
socket.on('enter',function(data){
showMessage(data,'enter');
});
socket.on('server',function(data){
showMessage(data,'server');
});
socket.on('leave',function(data){
showMessage(data,'leave');
});
function showMessage(str,type){
var div = document.createElement('div');
div.innerHTML = str;
document.body.appendChild(div);
if (type == 'enter') {
div.style.color='blue';
}else if (type=='leave') {
div.style.color='red';
};
}
</script>
</body>
</html>
The server is also very simple, sending client data when the connection is established, when the message is received and when the connection is closed
//Constant definition
var PORT = 3000
var clientCount = 0
//Monitor
var app = require('http').createServer()
var io = require('socket.io')(app);
app.listen(PORT);
io.on('connection', function (socket) {
console.log('new connection');
clientCount++;
socket.nickName='client'+clientCount;
io.emit('enter',socket.nickName+' comes in');
socket.on('client',function(data){
io.emit('server',socket.nickName+': '+data);
});
socket.on('disconnect',function(data){
console.log('disconnection');
io.emit('leave',socket.nickName+ ' left');
})
});
console.log("Socket.io Start..")