Home  >  Article  >  Web Front-end  >  Native nodejs uses websocket code sharing

Native nodejs uses websocket code sharing

亚连
亚连Original
2018-05-26 14:01:061589browse

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

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);
});
});

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>

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!

Statement:
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