Basic use of socket.io of WebSocket

 Socket.IO is a WebSocket library that enables low-latency, bi-directional, event-based communication between clients and servers. It is built on  top of the WebSocket  protocol and provides additional guarantees such as fallback to HTTP long polling or automatic reconnection.

basic use

Install socket.io

yarn add socket.io

 The contents of the new js file and html file are as follows

var http = require('http');
var io = require('socket.io');
var server = http.createServer((req,res)=>{
});
server.listen(2183);
// 监听 connection
io.listen(server).on('connection',(user)=>{
	setInterval(()=>{
		user.emit('test','哥们我主动来了'+Math.random());
	},1000);
});
<!doctype html> 
<html> 
<head> 
    <meta charset="utf-8">
    // 引用脚本,固定写法
    <script type="text/javascript" src='http://localhost:2183/socket.io/socket.io.js'></script> 
    <script type="text/javascript">
        // 连接服务
    	let connection = io.connect('ws://localhost:2183');

        connection.on('test',(str)=>{
    		console.log(str)
    	})
    </script>
    <title></title> 
</head>
<body>
</body>
</html>

After starting node at this time, the browser can open the html to see the information pushed by the server:

 

Now look at the above code,

on('connection',(user)=>{     setInterval(()=>{         user.emit('test', 'Dude, I'm here on my own initiative'+Math.random());     },1000); })



The user here is actually a user who is currently accessing the server. user.emit(key, value) is the method for the server to push messages to the front desk of the current user. The key is the unique identifier when receiving, and the value is the transmitted value.

Correspondingly, the method of receiving messages is on(key,()=>{}), and the push and receive methods are common in both the foreground and the server.

Foreground->Background
connection.emit(key,value)
connection.on(key,(str)=>{ }) Background->Foreground connection.emit(key,value) connection.on(key,(str)=>{  })




case study 

After understanding the basic usage, we can implement a small function, first create the html file as follows:

<!doctype html> 
<html> 
<head> 
    <meta charset="utf-8"> 
    <script type="text/javascript" src='http://localhost:2183/socket.io/socket.io.js'></script>
    <title></title> 
    <script type="text/javascript">
    	onload=()=>{
    		let conn=io.connect('ws://localhost:2183');
            // 点击按钮将输入框信息发送服务器
    		b.onclick = x=>{
    			conn.emit('msg',t.value)
    		};
            // 接收服务器消息并渲染
    		conn.on('msg',(str)=>{
    			var oLi = document.createElement('li');
    			oLi.innerHTML = str;
    			ul.appendChild(oLi);
    		})
    	}
    </script>
</head>
<body>
<input type="text" name="" id='t'>
<button id='b'>发送</button>
<ul id='ul'></ul>
</body>
</html>

1. Send a message on page A, and other online users B and C receive the message

We mentioned above that the background emit() can only be sent to the current user, so how to send it to other users, here we will use broadcast.emit()

io.listen(server).on('connection',(user)=>{
	user.on("msg",(str)=>{
		// 给除了自己的其他user发送
		user.broadcast.emit('msg',str);
	});
});

 Effect:

 2. When a user disconnects, push a message to other online users

user.on('disconnect',()=>{
	user.broadcast.emit('msg','有人下线了!')
});

3. Realize remote drag and drop (the effect is as follows)

<!doctype html> 
<html> 
<head> 
    <meta charset="utf-8"> 
    <script type="text/javascript" src='http://localhost:2183/socket.io/socket.io.js'></script>
    <title></title> 
    <style type="text/css">
    *{margin: 0;padding: 0;}
    #div1{width: 200px;height: 200px;background: rgb(182, 71, 123);position: absolute;border-radius: 50%;}
    </style>
    <script type="text/javascript">
    	onload =x=>{
    		var conn = io.connect('ws://localhost:2183');
    		conn.on('style',(json)=>{
    			div1.style.left = json.x+'px';
    			div1.style.top = json.y + 'px';
    		});
    		div1.onmousedown=function(e){
    			var ev = e || event;
    			var l = ev.clientX - this.offsetLeft;
    			var t = ev.clientY - this.offsetTop;
    			document.onmousemove = function(e){
    				var ev = e ||event;
    				var x = ev.clientX - l;
    				var y = ev.clientY - t;
    				conn.emit('divNode',{x:x,y:y})
    				this.style.left = x +'px';
    				this.style.top = y + 'px';
    			}.bind(this);
    			document.onmouseup = function(){
    				this.onmousemove = this.onmouseup = null;
    			};
    			return false;
    		}
    	};
    </script>
</head>
<body>
<div id='div1'></div>
</body>
</html>
var http = require('http');
var io = require('socket.io');

var server = http.createServer((req,res)=>{

});
server.listen(2183);

io.listen(server).on('connection',(user)=>{
	user.on('divNode',(json)=>{
		user.broadcast.emit('style',json);
	})

});

Summarize 

Using WebSocket can achieve a lot of interesting and practical functions, and then write an online chat room to consolidate the knowledge.

recommended reading 


[WeChat applet & uniapp series of articles]

[Vue Practical Plug-ins and Skills Series Articles]

Guess you like

Origin blog.csdn.net/G_ing/article/details/129651543