Showing posts with label script. Show all posts
Showing posts with label script. Show all posts

Monday, September 11, 2017

Game Tutorial using Node.js - IBM Bluemix (Part 2) [WebSocket Communication]

Hi folk,

In this part of the tutorial I will teach you how to implement the client-server part in a game with a few basic concepts using a basic connection model architecture, deploy the application in IBM Bluemix and how you can perform debugging tasks.

Let's start first with some basic concepts of WebSocket and the client-server architecture.

General concepts

WebSocket is a computer communication protocol communications protocol, providing full-duplex communication channels over a single TCP connection. WebSocket is designed to be implemented in web browsers and web servers, but it can be used by any client or server application.

The client-server architecture is a software design model in which tasks are shared between service providers or services, called servers, and callers, called clients. A client makes requests to another program, the server, which gives an answer.

To perform the requests and exchange data there is a concept called socket.
A socket designates an abstract concept by which two programs (possibly located on different computers) can interchange any data at a single node in a computer network.

Procedure

Before following the procedure, it is recommended to create the project structure described in previous post Game Tutorial using Nodejs - IBM Bluemix (Part 1).

So for the WebSocket communication, I'm going to use the Socket.IO library. Socket.IO enables real-time bidirectional event-based communication.

The procedure I followed in this part of the game tutorial is as follows:

1) Execute following command into project root folder to install node modules dependencies:
 
$ npm install socket.io           

2) Open file app.js and copy and paste following lines at the end:
 
// Socket communication
var io = require('socket.io')(server);

// Connect event
io.on('connection', function(socket){
  console.log('a user connected');
  // Disconnect event
  socket.on('disconnect', function(){
    console.log('user disconnected');
  });
});

3) Save file app.js
 4) Open file index.html and copy and paste following lines at the end:
 
<script src="/socket.io/socket.io.js"></script>
<script> 
var socket = io(); 
</script>

5) Save file index.html
6) Execute following command into project root folder to run local Express server:
 
$ node app.js

7) Open a browser a type localhost:3000


Once the connection is made from the client we will send a message to the server.


8) Open file index.html and copy and paste following into script tag:
 
// Send message to server
socket.emit('clientMsg',{
  msg:'Hi from browser client',
});

9) Save file index.html
10) Open file app.js and copy and paste following lines into ‘io’ connection function:
 
// Receive event message from client
socket.on('clientMsg', function(data){
  console.log(data.msg);
});

11) Save file app.js
12) Execute following command into project root folder to run local Express server:
 
$ node app.js

13) Open a browser a type localhost:3000


Finally, the server responds to the client with a return message.


14) Open file app.js and copy and paste following lines into ‘io’ connection function:
socket.emit('serverMsg',{
  msg:'Hi from browser server',
}); 

15) Save file app.js
16) Open file index.html and copy and paste following into script tag:
 
socket.on('serverMsg', function(data){
  console.log(data.msg);
});

17) Save file index.html
18) Execute following command into project root folder to run local Express server:
 
$ node app.js

19) Open a browser a type localhost:3000
20) Open browser Inspect tool.


Note: Most browsers currently have an inspection tool. In the case of Firefox the option is Inspect Element from the options menu of the page.

21) Execute following command into project root folder to push your app to Bluemix:
 
$ bluemix app push

Note: Deploying your application can take a few minutes. When deployment completes, you'll see a message that your app is running.

22) Open a browser and type {nameofyourapp}.mybluemix.net
23) Execute following command into project root folder to debug your app to Bluemix:
 
$ bluemix app logs {nameofyourapp}

Note: Debugging your application can take a few minutes the first time your invoke the service to retrieving logs. When deployment completes, you'll see your application traces log.


Second step done! now you can think something creative to create a game in the cloud.

You can download the sources of the example application here.
And you can also try the client example here.

Are you ready for the next part of the tutorial? Soon I publish it, be patient !!
Be blue, Be mix

Monday, September 4, 2017

Game Tutorial using Node.js - IBM Bluemix (Part 1)

Hi folk,

Many of you ask me to teach how to create a game in the cloud, I am preparing a tutorial step by step so everyone can realize their own game.

There is no better way to learn technological concepts than by playing with them.

Setup project local environment and deploy to Bluemix

What you'll need to build your game

Simple, all you need is:
  • Firefox (Browser)
  • Atom (Text Editor)   
  • NodeJS (Server)
  • Bluemix account (Hosting your game Online)


Project folder structure

A little theory about the project structure, folders and files so that throughout the tutorial people can identify the one we are modifying and why it is modified.


Install software

There is the software that you have to install:

Create project

Before to start the procedure you have to create a project structure with following folders and empty file


1) Open a terminal and go to project directory
2) Open the file package.json by command line (e.g.):
 
$ atom package.json

3) Copy and paste following lines:
 
{
  "name": "project",
  "version": "1.0.0",
  "description": "",
  "main": "app.js",
  "dependencies": {
    "express": "^4.13.4",
    "socket.io": "^1.4.5"
  },
  "devDependencies": {},
  "author": "",
  "license": "ISC",
  "scripts": {
      "start": "node app.js"
  }
}
 
4) Save file package.json
5) Execute following command into project root folder to install node modules dependencies:

$ npm install

New node_modules is added to project

6) Open file app.js
7) Copy and paste following lines:
  
 var http = require('http');
 var express = require('express');
 var app = express();
 
 app.get('/',function(req, res) {
  res.sendFile(__dirname + '/client/index.html');
 });

 app.use('/client',express.static(__dirname + '/client'));

 var server = http.createServer(app);
 server.listen(3000, function(){

   console.log('Express server listening on port ' + app.get('port'));

 });
 
8) Save file app.js
9) Open files index.html
10) Write following line:
 
Hello Folk! Start game here!

11) Save file index.html
12) Execute following command into project root folder to run local Express server:
 
 $ node app.js

13) Open a browser and type:
 
http://localhost:3000

The result:



Try: You can access to client files
http://localhost:3000/client/img/lock.png

Deploy to Bluemix

Now is time to host the application to the cloud.

1) Open a terminal and go to project directory
2) Connect and log in to Bluemix using your account:
 
$ bluemix api https://api.ng.bluemix.net

3) Open file manifest.yml
4) Copy and paste following lines:
 
 applications:
 - path: .
  memory: 512M
  instances: 1
  domain: mybluemix.net
  name: tgbm
  host: {write-your-unique-hostname}
  disk_quota: 1024M
 
 5) Update the host property with your own host name

Note: In this manifest.yml file, random-route: true property generates a random route for your app to prevent your route from colliding with others. If you choose to, you can replace random-route: true with host:{write-your-unique-hostname}, supplying a host name of your choice

6) Save file manifest.yml
7) Execute following command into project root folder to push your app to Bluemix.
 
$ bluemix app push

Note: Deploying your application can take a few minutes. When deployment completes, you'll see a message that your app is running

 
8) Open a browser and type:
 
http://tuto-game-bx.mybluemix.net

The result:
Yeah!!! Your are ready for the next part of this tutorial!!

Let's go then, click here.
Be blue, be mix

Friday, June 7, 2013

Check Percentage of CPU usage - Linux

Hi folk,

A couple of days ago, I did not know that one of my CPU was running at 100% capacity because a process was "hung".





So, I had to make a Kill -9, but to my surprise, the next day I had the same problem.

Once I solved the problem I kept thinking, how many times did this happen with other process on my laptop and I have not noticed?

To stay informed I have created the following bash script to check the top 10 processes.

#!/bin/sh
# Check Percentage of CPU usage
# Jorge Iglesias

# Skip first lines from top command with head -17
# PID USER      PR  NI  VIRT  RES  SHR S %CPU %MEM    TIME+  COMMAND
# Select top ten proccess with -n 10
top -n1 -b | head -17 | tail -n 10 > top.txt

while read line
do
    ind=0
    pid=""

    for line in $line;
    do
        if [ $ind -eq 0 ]    # index of PID
        then
            pid=$line
          
        fi

        if [ $ind -eq 8 ]    # index of %CPU
        then
            min=80.0     # min value alert
            if [ 1 -eq `echo "${line} > ${min}" | bc` ]
            then
                notify-send -t 5000 -i error "Percentage of CPU usage" "The %CPU usage for process <b>id $pid</b> is <b>$line%</b> \n\nPlease review and kill the process."      
            fi
            break;         # break line, only read to %CPU value
        fi
        ((ind+=1))
    done
done < top.txt

rm top.txt                # delete temp file


I scheduled the script to run every 10 minutes and when it detects that a process up to 80% then is reported on screen.

 
You can watch the process using the top command.


Now, you decide if you really want to "kill" the process or not :-)

I hope this helps!!

Cheers.

Monday, February 25, 2013

WebSphere launch commands utility for Linux Test Environment

Hi folk,

Right now, I'm working on a project where I have to do performance tests in J2EE applications with continually stopping and starting the application server.

I created a bash script based on a set of WAS command line for people with short memory, like me ;-)



I want to share the script that we use to facilitate our work. 

I hope this helps.
 
#!/bin/sh
# Launch Websphere Application Server - HTTPServer
# Jorge Iglesias

# Note: Launch with root permission
if [ "$(whoami)" != 'root' ]; then
    echo "You have no permission to run $0 as non-root user"
        exit 1;
fi

# Define variables
WAS_DMGR=dmgr
WAS_SERVER_NODE=nodeagent
WAS_SERVER=server1
PATH_WAS=/opt/IBM/WebSphere/AppServer
PATH_WAS_DMGR_PROFILE=${PATH_WAS}/profiles/Dmgr01
PATH_WAS_SERVER_PROFILE=${PATH_WAS}/profiles/AppSrv01
LOG_WAS_DMGR=${PATH_WAS_DMGR_PROFILE}/logs/$WAS_DMGR/SystemOut.log
LOG_WAS_SERVER_NODE=${PATH_WAS_SERVER_PROFILE}/logs/$WAS_SERVER_NODE/SystemOut.log
LOG_WAS_SERVER=${PATH_WAS_SERVER_PROFILE}/logs/$WAS_SERVER/SystemOut.log
WAS_USER=wasadmin
WAS_PWD=passw0rd
PATH_HTTPSERVER=/opt/IBM/HTTPServer

# Funciones
OpenLogFile ()
{
    # Check params:
    # LOG_FILE: log file
    # LOG_FILE_TITLE: log file title

    proc=$(xlsclients -a | grep SystemOut.log)

    if [ -z "${proc}" ]
    then
    {
        TAIL_FILE="tail -f ${LOG_FILE}"
        gnome-terminal --title "${LOG_FILE_TITLE}" -e "${TAIL_FILE}" &
    }
    fi
}

CloseLogFile ()
{
    proc=$(xlsclients -a | grep gnome-terminal | grep SystemOut.log)

    if [ ! -z "${proc}" ]
    then
    {
        kill -9 `ps -eaf | grep gnome-terminal | grep SystemOut.log | awk '{ print $2 }'`
    }
    fi
}

InitServer ()
{
    # Check params:
    # TMP_CMD: command to exec
    # TMP_FILE: pid file
  
    echo "Starting server: $TMP_FILE"

    # exists PID file?  
    if [ -f $TMP_FILE ]
    then
    {
        PID=`cat $TMP_FILE`
         echo "Server with PID:"$PID

            echo "Restart server (y/n)?"

        printf "> "
        read quest
        case $quest in
          y)
            StartServer;;
        Y)
            StartServer;;
        N)
            ;;
          n)
            ;;
        esac

    }
    else
    {
        StartServer
    }  
    fi
}

StartServer()
{
    # Start server
    # &, run background
    # $TMP_CMD &      
    $TMP_CMD      
  
    IS_STARTED=0
    while [ $IS_STARTED = 0 ]
    do {
        # wait one second
        sleep 1
        if [ -f $TMP_FILE ]
        then
        {
            IS_STARTED=1
        }
        else
        {
            IS_STARTED=0
        }
        fi
    }
    done
}

StopServer ()
{
    # Check params:
    # TMP_CMD: command to exec
    # TMP_FILE: pid file

    echo "Stoping server: $TMP_FILE"

    # exists PID file?  
    if [ -f $TMP_FILE ]
    then
    {
        # Stop server
        # &, run background
        # $TMP_CMD &      
        $TMP_CMD      
      
        IS_STARTED=0
        while [ $IS_STARTED = 0 ]
        do {
            # wait one second
            sleep 1

            if [ -f $TMP_FILE ]
            then
            {
                IS_STARTED=0
            }
            else
            {
                IS_STARTED=1
            }
            fi
        }
        done
    }
    else
    {
         echo "Server stopped."
    }  
    fi
}

SetStartDmgrParams ()
{
    LOG_FILE_TITLE="Fichero de trazas: $WAS_DMGR"
    LOG_FILE=$LOG_WAS_DMGR
    TMP_CMD=$PATH_WAS_DMGR_PROFILE/bin/startManager.sh
    TMP_FILE=$PATH_WAS_DMGR_PROFILE/logs/$WAS_DMGR/$WAS_DMGR.pid
}

SetStartAppSrvNodeParams ()
{
    LOG_FILE_TITLE="Fichero de trazas: $WAS_SERVER_NODE"
    LOG_FILE=$LOG_WAS_SERVER_NODE
    TMP_CMD=$PATH_WAS_SERVER_PROFILE/bin/startNode.sh
    TMP_FILE=$PATH_WAS_SERVER_PROFILE/logs/$WAS_SERVER_NODE/$WAS_SERVER_NODE.pid
}

SetStartAppSrvParams ()
{
    LOG_FILE_TITLE="Fichero de trazas: $WAS_SERVER"
    LOG_FILE=$LOG_WAS_SERVER
    TMP_CMD="$PATH_WAS_SERVER_PROFILE/bin/startServer.sh server1"
    TMP_FILE=$PATH_WAS_SERVER_PROFILE/logs/$WAS_SERVER/$WAS_SERVER.pid
}

SetStopDmgrParams ()
{
    LOG_FILE_TITLE="Fichero de trazas: $WAS_DMGR"
    LOG_FILE=$LOG_WAS_DMGR
    TMP_CMD="$PATH_WAS_DMGR_PROFILE/bin/stopManager.sh -username $WAS_USER -password $WAS_PWD"
    TMP_FILE=$PATH_WAS_DMGR_PROFILE/logs/$WAS_DMGR/$WAS_DMGR.pid
}

SetStopAppSrvNodeParams ()
{
    LOG_FILE_TITLE="Fichero de trazas: $WAS_SERVER_NODE"
    LOG_FILE=$LOG_WAS_SERVER_NODE
    TMP_CMD="$PATH_WAS_SERVER_PROFILE/bin/stopNode.sh -username $WAS_USER -password $WAS_PWD"
    TMP_FILE=$PATH_WAS_SERVER_PROFILE/logs/$WAS_SERVER_NODE/$WAS_SERVER_NODE.pid
}

SetStopAppSrvParams ()
{
    LOG_FILE_TITLE="Fichero de trazas: $WAS_SERVER"
    LOG_FILE=$LOG_WAS_SERVER
    TMP_CMD="$PATH_WAS_SERVER_PROFILE/bin/stopServer.sh $WAS_SERVER -username $WAS_USER -password $WAS_PWD"
    TMP_FILE=$PATH_WAS_SERVER_PROFILE/logs/$WAS_SERVER/$WAS_SERVER.pid
}

StartWebserver ()
{
    echo "Start HTTPServer"
    TMP_CMD="$PATH_HTTPSERVER/bin/apachectl -k start"
    $TMP_CMD
}

StopWebserver ()
{
    echo "Stop HTTPServer"
    TMP_CMD="$PATH_HTTPSERVER/bin/apachectl -k stop"
    $TMP_CMD
}

ExitProcess ()
{
    # TODO
    # Check StopServer

    # TODO
    # Check CloseLogFile
      
    exit 1;
}

ShowMenu ()
{  
    # clear  
    echo ""
    echo "-------------------------"
    echo "* Process - Launch WAS Menu"
    echo "1 - Start dmgr-nodeagent-server1-httpserver"
        echo "2 - Start dmgr"
        echo "3 - Start nodeagent"
        echo "4 - Start server1"
        echo "5 - Stop dmgr"
        echo "6 - Stop nodeaget"
        echo "7 - Stop server1"
    echo "8 - Stop httpserver-server1-nodeagent-dmgr"
    echo "-------------------------"
        echo "10 - Start HTTPServer"
        echo "11 - Stop HTTPServer"
    echo ""

        echo "99 - Exit"

    printf "> "
    read num
    case $num in
      1)
        SetStartDmgrParams;      
        OpenLogFile;
         InitServer;

        SetStartAppSrvNodeParams;
        OpenLogFile;
         InitServer;

        SetStartAppSrvParams;
        OpenLogFile;
         InitServer;

         StartWebserver;;
    2)
        SetStartDmgrParams;      
        OpenLogFile;
         InitServer;;
    3)
        SetStartAppSrvNodeParams;
        OpenLogFile;
         InitServer;;
    4)
        SetStartAppSrvParams;
        OpenLogFile;
         InitServer;;
    5)
        SetStopDmgrParams;      
        CloseLogFile;
        StopServer;;
    6)
        SetStopAppSrvNodeParams;
        CloseLogFile;
        StopServer;;
    7)
        SetStopAppSrvParams;
        OpenLogFile;
         StopServer;;
    8)
         StopWebserver;

        SetStopAppSrvParams;
        CloseLogFile;
        StopServer;

        SetStopAppSrvNodeParams;
        CloseLogFile;
        StopServer;

        SetStopDmgrParams;      
        CloseLogFile;
        StopServer;;
    10)
         StartWebserver;;
    11)
         StopWebserver;;
      99)
        ExitProcess;;
    esac
  
    # back to menu
    ShowMenu
}

ShowMenu

Wednesday, July 25, 2012

Search files within a ZIP archive using zipgrep tool

Bash script that search files within a ZIP archive for lines matching given string or pattern using zipgrep tool.

#!/bin/sh
# zipgrep Util 0.1
# Result ziprep by directory file
# @Jorge Iglesias

# Note: root users
if [ "$(whoami)" != 'root' ]; then
    echo "You have no permission to run $0 as non-root user"
        exit 1;
fi

clear
echo "zipgrep Util 0.1"
echo "Jorge Iglesias"
echo "----------------"

echo "Input pattern"
printf "> "
read pattern

echo "Input directory grep"
printf "> "
read directory

echo "Input directory output results"
printf "> "
read directoryOut

# Control will enter here if $DIRECTORY doesn't exist.
if [ ! -d "$directoryOut" ]; then
    mkdir $directoryOut
fi

cd $directory


index=0

for file in `dir -d *` ; do
    index=$((index+1))
    zipgrep $pattern $file > $directoryOut/$file.out
    # Control file size and delete files with size 0
    fileSize=$(stat -c "%s" $directoryOut/$file.out)
    if [ $fileSize = 0 ]; then {
        index=$((index-1))
        rm $directoryOut/$file.out
    }
    fi
done

echo "Pattern found in $index files."

Monday, July 23, 2012

How to convert .ico files to .png - Linux

# convert start_server.ico start_server.png
bash: convert: command not found...
Install package 'ImageMagick' to provide command 'convert'? [N/y]
 * Running..
 * Resolving dependencies..
 * Waiting for authentication..
 * Waiting in queue..
 * Resolving dependencies..
 * Downloading packages..
 * Testing changes..
 * Installing packages..
 * Scanning applications..

# convert start_server.ico start_server.png