NodeJS Tutorial Part 2 - Socket.IO

in #utopian-io6 years ago

NODEJS


Repository

https://github.com/nodejs/node
https://github.com/socketio/socket.io

What Will I Learn?

  • using Socket.IO to transfer data between the client and the server

Requirements

  • basic knowledge of javascript programming

Difficulty

  • Basic

Tutorial Contents

first install the socket.io, express and steem package
npm install steem express socket.io --save
it will install it automatically to your folder, just open the command line at the project folder

First we will create the html file,
the html file is simple just like anything else but we'll use some scripts

so first create the file

<!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">
    <title>Test Socket.IO</title>
</head>
<body>
</body>
</html>

now at the body add this scripts - Jquery & Socket.io
and connect to the socket.io server that we will create later

    <script
        src="https://code.jquery.com/jquery-3.3.1.min.js"
        integrity="sha256-FgpCb/KJQlLNfOu91ta32o/NMZxltwRo8QtmkMRdAu8="
        crossorigin="anonymous"></script>
    <script src = "https://cdnjs.cloudflare.com/ajax/libs/socket.io/2.2.0/socket.io.slim.js"></script>
    <script>
        var socket = io.connect('http://localhost:8000');
    </script>

so we're adding the script of jquery from the jquery CDN, same for the socket.io

then we're creating our own script tag and creating the variable socket and creating connection with the socket.io server.

now add input text and button to interact with the server

  <input type="text" id="url-steem" placeholder="STEEM URL" />
    <button id="sendVote">VOTE!</button>

we will use steem url to send vote by socket.io, we will send the data to the server through socket.io and get a feedback through socket.io aswell

now just add a little bit of javascript to the html
on our script -

        $("#sendVote").click(function(){
            socket.emit("sendVote", $("#url-steem").val());
        });

first we will check if the button is clicked, if it is we will send emit to the server with the steem URL

        socket.on("vote_sucess", function(){
            $("body").append("<p>Voted Successfully!</p>");
        });

now it's for the feedback, when we will get this emit we will update the body and add a p tag with the text of voted succesfully so we will get any kind of feedback, because it's simple tutorial we don't going for design or something like that.

okay we're already done with the client side, now let's go for the server side

here we're need to add http, express, steem, path and socket.io

just copy it and look later

var app = require('express')(),
    express = require('express'),
    http = require('http').Server(app),
    io = require('socket.io')(http),
    steem = require('steem'),
    path = require('path');

now we will use express to be able to access our index.html file

app.use(express.static(path.resolve('')));

just like in the first tutorial we're calling the function app.use to use a specific data and giving it our folder so we can access all of the files, for this it's index.html file.

now add weight variable and account & wif.

var weight = 100;

var acc = "guest123",
    wif = "5JRaypasxMx1L97ZUX7YuC5Psb5EAbF821kkAGtBj7xCJFQcbLg";

you can use any integer for weight from 1-100, up to 100% as you know.

the account is the steemjs guest account which using for voting, commenting and some more stuff, we're using POSTING WIF here.

now create vote function

function vote(account, wif, author, permlink, weight, socket) {
    steem.broadcast.vote(wif, account, author, permlink, weight, function(err, result) { //"broadcast" the vote to the blockchain
        if(err)
            throw err;
        
        socket.emit("vote_sucess");
        console.log('Voted Succesfully, permalink: ' + permlink + ', author: ' + author + ', weight: ' + weight / 100 + '%.');
    });
}

we're taking the account name, wif, the author of the post, the permlink of the post, the weight and socket, which is using for socket.io so we can send feedback when the broadcast ends.

now we're sending a broadcast type vote to the blockchain with all of the details and then sending an emit to the client and telling that the vote is made succesfully.
and sending comment to the console.

at the bottom of the script make a listen to the http server so we will be able to connect to the server.

http.listen(8000, function(){
    console.log('listening to port 8000!');
    console.log('server running...');
    console.log('===========================');
});

now to use socket.io we need to check first if we have a socket connection

io.on('connection', function(socket){
    console.log("socket connected");
});

now when you will connect to the client it will say that the socket is connected

console :

listening to port 8000!
server running...
=====================
socket connected

now all you need to do is to get the emit sendVote and send the vote, pretty easy right?

    socket.on("sendVote", function(url){
        url = url.split('/');
        author = url[4],
        permlink = url[5];
        author = author.split('@')[1];
        vote(acc, wif, author, permlink, weight*100, socket);
    });

so we're getting the emit, spliting the url with salshes, getting the author which is at the four split and permlink which is in the five split,
defaultly we're getting the author with @upmeboost for example, so we're deleting it by spliting it and getting the 1 split.
now all we need to do is to use the vote function with our account, wif key, author, permlink, weight and socket variable.

and here we're done.
all you need to do is to run the script and that's it!

I'm sorry that this tutorial is not detailed explained, I really trying to improve that !

Curriculum

Proof of Work Done

https://github.com/upmeboost-utopian

Sort:  

Thank you for your contribution @upmeboost.
We've been reviewing your tutorial, and we've suggested the following points for you to improve on your next tutorial:

  • Code sections are important to have comments. It will help a lot of users who are less experienced.

  • Your tutorial is quite short for a good tutorial. We recommend you aim for capturing at least 2-3 concepts.

  • There are already some tutorials explaining how to make a vote script in steemit, but by socket we find it interesting.

  • Improve your tutorial writing. In a tutorial it is very important the text to be well written, so that the reader understands well what it is explaining.

  • In the tutorials it's very important to also have theory about what you are explaining. If it only contains practice, the user will not perfectly understand what he will develop.

We hope you keep these points in mind in your next tutorial.
Looking forward to your upcoming tutorials.

Your contribution has been evaluated according to Utopian policies and guidelines, as well as a predefined set of questions pertaining to the category.

To view those questions and the relevant answers related to your post, click here.


Need help? Write a ticket on https://support.utopian.io/.
Chat with us on Discord.
[utopian-moderator]

Thanks.
What do you mean about theory? I can't understand what Im missing.

Thank you for your review, @portugalcoin! Keep up the good work!

Congratulations! This post has been upvoted from the communal account, @minnowsupport, by TheRealWolF🐺 from the Minnow Support Project. It's a witness project run by aggroed, ausbitbank, teamsteem, someguy123, neoxian, followbtcnews, and netuoso. The goal is to help Steemit grow by supporting Minnows. Please find us at the Peace, Abundance, and Liberty Network (PALnet) Discord Channel. It's a completely public and open space to all members of the Steemit community who voluntarily choose to be there.

If you would like to delegate to the Minnow Support Project you can do so by clicking on the following links: 50SP, 100SP, 250SP, 500SP, 1000SP, 5000SP.
Be sure to leave at least 50SP undelegated on your account.

Hi @upmeboost!

Your post was upvoted by @steem-ua, new Steem dApp, using UserAuthority for algorithmic post curation!
Your post is eligible for our upvote, thanks to our collaboration with @utopian-io!
Feel free to join our @steem-ua Discord server

Hey, @upmeboost!

Thanks for contributing on Utopian.
We’re already looking forward to your next contribution!

Get higher incentives and support Utopian.io!
Simply set @utopian.pay as a 5% (or higher) payout beneficiary on your contribution post (via SteemPlus or Steeditor).

Want to chat? Join us on Discord https://discord.gg/h52nFrV.

Vote for Utopian Witness!

Coin Marketplace

STEEM 0.18
TRX 0.15
JST 0.028
BTC 63768.57
ETH 2478.16
USDT 1.00
SBD 2.54