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

How to implement WebSocket function using NodeJS

亚连
Release: 2018-06-06 11:30:34
Original
1574 people have browsed it

This article mainly introduces the simple implementation of WebSocket function by NodeJS, and analyzes the client-side and server-side operation skills of nodejs to implement WebSocket communication function based on specific examples. Friends in need can refer to the examples of this article

Describes the simple implementation of WebSocket function in NodeJS. Share it with everyone for your reference, the details are as follows:

We develop based on express and socket.io. First we need to install the following packages

npm install --save express
npm install --save socket.io
Copy after login

Server-side code:

var app = require('express')();
var http = require('http').Server(app);
var io = require('socket.io')(http);
app.get('/', function(req, res){
  res.send(&#39;<h1>Welcome Realtime Server</h1>&#39;);
});
io.on(&#39;connection&#39;, function(socket){
  console.log(&#39;a user connected&#39;);
  socket.on("disconnect", function() {
    console.log("a user go out");
  });
  socket.on("message", function(obj) {
    io.emit("message", obj);
  });
});
http.listen(3000, function(){
  console.log(&#39;listening on *:3000&#39;);
});
Copy after login

Client-side code

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Document</title>
  <script src="http://127.0.0.1:3000/socket.io/socket.io.js"></script>
</head>
<body>
  <ul id="message"></ul>
  <script>
    socket = io.connect(&#39;ws://127.0.0.1:3000&#39;);
    socket.emit("message", {"name" : navigator.userAgent, "msg" : "hello world"});
    socket.on("message", function(obj) {
      console.log(obj);
    });
  </script>
</body>
</html>
Copy after login

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

Related articles:

How to use puppeteer to crack the sliding verification code of JiExperience

Bind dynamically generated tags in jquery Event (detailed tutorial)

How to change page color in JS (detailed tutorial)

The above is the detailed content of How to implement WebSocket function using NodeJS. 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!