Home >Web Front-end >JS Tutorial >Native nodejs uses websocket code sharing
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('Connection to server opened'); sendMessage(); } function sendMessage() { ws.send('hello'); } </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!