Home > Web Front-end > JS Tutorial > How NodeJS implements WebSocket function

How NodeJS implements WebSocket function

php中世界最好的语言
Release: 2018-04-12 16:57:27
Original
4122 people have browsed it

This time I will show you how NodeJS implements the WebSocket function. What are the precautions for NodeJS to implement the WebSocket function. The following is a practical case, let's take a look.

We develop based on express and socket.io. First we need toinstallthe 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('<h1>Welcome Realtime Server</h1>');
});
io.on('connection', function(socket){
  console.log('a user connected');
  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('listening on *:3000');
});
Copy after login

Client 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('ws://127.0.0.1:3000');
    socket.emit("message", {"name" : navigator.userAgent, "msg" : "hello world"});
    socket.on("message", function(obj) {
      console.log(obj);
    });
  </script>
</body>
</html>
Copy after login

A console version of the chat room is ready (^o^)/~

I believe you have mastered the method after reading the case in this article. For more exciting information, please pay attention to other related articles on the PHP Chinese website!

Recommended reading:

How to achieve the undo and redo effect in Immutable.js

Detailed explanation of the use of mutations and actions in Vuex

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