Home > Web Front-end > JS Tutorial > body text

Native nodejs uses websocket code sharing

亚连
Release: 2018-05-26 14:01:06
Original
1637 people have browsed it

This article shares with you how to use websocket to realize information transmission in native nodejs. It is very practical. Friends in need can refer to

Installation:

npm  install  ws
Copy after login

Server (nodejs):

var WebSocketServer = require('ws').Server,
wss = new WebSocketServer({ port: 8080 });
wss.on('connection', function (ws) {
console.log('client connected');
ws.on('message', function (message) {
  console.log(message);
});
});
Copy after login

Client:

<script>
var ws = new WebSocket("ws://localhost:8080");
ws.onopen = function (e) {
  console.log(&#39;Connection to server opened&#39;);
  sendMessage();
}
function sendMessage() {
  ws.send(&#39;hello&#39;);
}
</script>
Copy after login

The above is what I compiled for everyone. I hope it will be helpful to everyone in the future.

Related articles:

Ajax method to regularly update a certain piece of content on the page

Ajax gets the length of the response content Method

Ajax method of traversing xml document

##

The above is the detailed content of Native nodejs uses websocket code sharing. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!