Форум программистов, компьютерный форум, киберфорум
Наши страницы
8Observer8
Войти
Регистрация
Восстановить пароль
Рейтинг: 5.00. Голосов: 1.

Emit and Broadcast JSON using Socket.io and JS/ES5

Запись от 8Observer8 размещена 17.02.2019 в 18:36

I will show differences between "emit" and "broadcast" on server side.

In short:
  • "emit" sends JSON data to a connected client
  • "broadcast" sends JSON data to every client except the connected client

At first time create a connection between the server and the client using this instruction: 101. Socket.io Connection, JS/ES5

We have this callback function in "app.js":

Javascript
1
2
3
4
io.sockets.on("connection", function(socket)
{
    console.log("client was connected");
});
We will generate a name for a connected client on the server side. Client will get his own name from the server and will show it on the screen in a browser. We will use "shortid" module for generation names for clients.

Install "shortid" package. Type this command in the console from your project folder: npm install --save shortid

We will use "shortid" module to generate a random unique name. Let's show generated name:

app.js

Javascript
1
2
3
4
5
6
7
var shortid = require('shortid');
 
io.sockets.on("connection", function(socket)
{
   var clientName = shortid.generate();
    console.log("client was connected, name = " + clientName);
);
You will see a message in the console, like this:

Цитата:
client was connected, name = 3fPIOl61W
Let's create two buttons: "Get My Name" and "Send my Name to all Clients". Copy this code to server and to client sides. Do not forget to run the server by command: node app.js After this you need to open two clients in different browser tabs: http://localhost:8080/. Open the browser console, for example in Chrome: "Ctrl+Shift+J" and clear "cache" by RMB on "Reload" button and select "Empty Cache and Hard Reload". And do not forget reload the server when you made changes on the server side code.

app.js

Javascript
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
var express = require("express");
var app = express();
var server = require("http").Server(app);
 
app.get("/", function(req, res)
{
    res.sendFile(__dirname + "/client/index.html");
});
app.use("/client", express.static(__dirname + "/client"));
 
var port = 8080;
server.listen(port);
console.log("Server started. Port = " + port);
 
var io = require("socket.io")(server, {});
var shortid = require('shortid');
 
io.sockets.on("connection", function(socket)
{
    var clientName = shortid.generate();
    console.log("client was connected, name = " + clientName);
 
    socket.on("getMyName", function()
    {
        socket.emit("onGetMyName", { name: clientName });
    });
 
    socket.on("sendMyNameToAllClients", function()
    {
        socket.broadcast.emit("onSendMyNameToAllClients", { name: clientName });
        console.log(clientName);
    });
});
index.html

PHP/HTML
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
<!DOCTYPE html>
<html lang="en">
 
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <script src="https://cdnjs.cloudflare.com/ajax/libs/socket.io/2.2.0/socket.io.js"></script>
    <title>Multiplayer Snake</title>
</head>
 
<body>
    <button onclick="getMyName();">Get My Name</button>
    <button onclick="sendMyNameToAllClients();">Send my Name to all Clients</button>
    <script>
        var socket = io();
 
        socket.emit("hello", { message: "hello from client!" });
 
        socket.on("onGetMyName", function(data)
        {
            console.log("My Name: " + data.name);
        });
 
        socket.on("onSendMyNameToAllClients", function(data)
        {
            console.log("Name of another client: " + data.name);
        });
 
        function getMyName()
        {
            socket.emit("getMyName");
        }
 
        function sendMyNameToAllClients()
        {
            socket.emit("sendMyNameToAllClients");
        }
    </script>
</body>
 
</html>
Размещено в Без категории
Просмотров 114 Комментарии 1
Всего комментариев 1
Комментарии
  1. Старый комментарий
    Запись от 8Observer8 размещена 17.02.2019 в 20:58 8Observer8 вне форума
 
КиберФорум - форум программистов, компьютерный форум, программирование
Powered by vBulletin® Version 3.8.9
Copyright ©2000 - 2019, vBulletin Solutions, Inc.
Рейтинг@Mail.ru