Saturday, 21 December 2013

Socket programming with sending message and error handling

Php and tcp/ip sockets
This is a quick guide/tutorial to learning socket programming in php. Socket programming php is very similar to C. Most functions are similar in names, parameters and output. However unlike C, socket programs written in php would run the same way on any os that has php installed. So the code does not need any platform specific changes (mostly).
To summarise the basics, sockets are the fundamental "things" behind any kind of network communications done by your computer. For example when you type www.google.com in your web browser, it opens a socket and connects to google.com to fetch the page and show it to you. Same with any chat client like gtalk or skype. Any network communication goes through a socket.
Before you begin
This tutorial assumes that you already know php and also how to run php scripts from the commandline/terminal. Php scripts are normally run from inside the browser by placing them in the apache root directory like /var/www. However these commandline programs can be run from any directory. They can be run from browsers as well.
So lets begin with sockets.
Creating a socket
This first thing to do is create a socket. The socket_create function does this.
Here is a code sample :
1
$sock = socket_create(AF_INET, SOCK_STREAM, 0);
Function socket_create creates a socket and returns a socket descriptor which can be used in other network commands.
The above code will create a socket with the following properties ...
Address Family : AF_INET (this is IP version 4)
Type : SOCK_STREAM (this means connection oriented TCP protocol)
Protocol : 0 [ or IPPROTO_IP This is IP protocol]
Error handling
If any of the socket functions fail then the error information can be retrieved using the socket_last_error and socket_strerror functions.
if(!($sock = socket_create(AF_INET, SOCK_STREAM, 0)))
{
    $errorcode = socket_last_error();
    $errormsg = socket_strerror($errorcode);
     
    die("Couldn't create socket: [$errorcode] $errormsg \n");
}

echo "Socket created";
Ok , so you have created a socket successfully. But what next ? Next we shall try to connect to some server using this socket. We can connect to www.google.com
Note
Apart from SOCK_STREAM type of sockets there is another type called SOCK_DGRAM which indicates the UDP protocol. This type of socket is non-connection socket. In this tutorial we shall stick to SOCK_STREAM or TCP sockets.
Connect to a Server
We connect to a remote server on a certain port number. So we need 2 things , IP address and port number to connect to. So you need to know the IP address of the remote server you are connecting to. Here we used the ip address of google.com as a sample. A little later on we shall see how to find out the ip address of a given domain name.
The last thing needed is the connect function. It needs a socket and a sockaddr structure to connect to. Here is a code sample.
if(!($sock = socket_create(AF_INET, SOCK_STREAM, 0)))
{
    $errorcode = socket_last_error();
    $errormsg = socket_strerror($errorcode);
     
    die("Couldn't create socket: [$errorcode] $errormsg \n");
}

echo "Socket created \n";

if(!socket_connect($sock , '74.125.235.20' , 80))
{
    $errorcode = socket_last_error();
    $errormsg = socket_strerror($errorcode);
     
    die("Could not connect: [$errorcode] $errormsg \n");
}

echo "Connection established \n";
Run the program
$ php /var/www/socket.php
Socket created
Connection established
It creates a socket and then connects. Try connecting to a port different from port 80 and you should not be able to connect which indicates that the port is not open for connection. This logic can be used to build a port scanner.
OK, so we are now connected. Lets do the next thing , sending some data to the remote server.
Quick Note
The concept of "connections" apply to SOCK_STREAM/TCP type of sockets. Connection means a reliable "stream" of data such that there can be multiple such streams each having communication of its own. Think of this as a pipe which is not interfered by other data.
Other sockets like UDP , ICMP , ARP dont have a concept of "connection". These are non-connection based communication. Which means you keep sending or receiving packets from anybody and everybody.
Sending Data
Function send will simply send data. It needs the socket descriptor , the data to send and its size.
Here is a very simple example of sending some data to google.com ip :

if(!($sock = socket_create(AF_INET, SOCK_STREAM, 0)))
{
    $errorcode = socket_last_error();
    $errormsg = socket_strerror($errorcode);
     
    die("Couldn't create socket: [$errorcode] $errormsg \n");
}

echo "Socket created \n";

//Connect socket to remote server
if(!socket_connect($sock , '74.125.235.20' , 80))
{
    $errorcode = socket_last_error();
    $errormsg = socket_strerror($errorcode);
     
    die("Could not connect: [$errorcode] $errormsg \n");
}

echo "Connection established \n";

$message = "GET / HTTP/1.1\r\n\r\n";

//Send the message to the server
if( ! socket_send ( $sock , $message , strlen($message) , 0))
{
    $errorcode = socket_last_error();
    $errormsg = socket_strerror($errorcode);
     
    die("Could not send data: [$errorcode] $errormsg \n");
}

echo "Message send successfully \n";
In the above example , we first connect to an ip address and then send the string message "GET / HTTP/1.1\r\n\r\n" to it.
The message is actually a http command to fetch the mainpage of a website.
Now that we have send some data , its time to receive a reply from the server. So lets do it.
Note
When sending data to a socket you are basically writing data to that socket. This is similar to writing data to a file. Hence you can also use the write function to send data to a socket. Later in this tutorial we shall use write function to send data.
Receiving Data
Function recv is used to receive data on a socket. In the following example we shall send the same message as the last example and receive a reply from the server.
<?php

if(!($sock = socket_create(AF_INET, SOCK_STREAM, 0)))
{
    $errorcode = socket_last_error();
    $errormsg = socket_strerror($errorcode);
     
    die("Couldn't create socket: [$errorcode] $errormsg \n");
}

echo "Socket created \n";

//Connect socket to remote server
if(!socket_connect($sock , '74.125.235.20' , 80))
{
    $errorcode = socket_last_error();
    $errormsg = socket_strerror($errorcode);
     
    die("Could not connect: [$errorcode] $errormsg \n");
}

echo "Connection established \n";

$message = "GET / HTTP/1.1\r\n\r\n";

//Send the message to the server
if( ! socket_send ( $sock , $message , strlen($message) , 0))
{
    $errorcode = socket_last_error();
    $errormsg = socket_strerror($errorcode);
     
    die("Could not send data: [$errorcode] $errormsg \n");
}

echo "Message send successfully \n";

//Now receive reply from server
if(socket_recv ( $sock , $buf , 2045 , MSG_WAITALL ) === FALSE)
{
    $errorcode = socket_last_error();
    $errormsg = socket_strerror($errorcode);
     
    die("Could not receive data: [$errorcode] $errormsg \n");
}

//print the received message
echo $buf;
Here is the output of the above code :
$ php /var/www/socket.php
Socket created
Connection established
Message send successfully
HTTP/1.1 302 Found
Cache-Control: private
Content-Type: text/html; charset=UTF-8
Set-Cookie: expires=; expires=Mon, 01-Jan-1990 00:00:00 GMT; path=/; domain=www.google.com
Set-Cookie: path=; expires=Mon, 01-Jan-1990 00:00:00 GMT; path=/; domain=www.google.com
Set-Cookie: domain=; expires=Mon, 01-Jan-1990 00:00:00 GMT; path=/; domain=www.google.com
Set-Cookie: expires=; expires=Mon, 01-Jan-1990 00:00:00 GMT; path=/; domain=.www.google.com
Set-Cookie: path=; expires=Mon, 01-Jan-1990 00:00:00 GMT; path=/; domain=.www.google.com
Set-Cookie: domain=; expires=Mon, 01-Jan-1990 00:00:00 GMT; path=/; domain=.www.google.com
Set-Cookie: expires=; expires=Mon, 01-Jan-1990 00:00:00 GMT; path=/; domain=google.com
Set-Cookie: path=; expires=Mon, 01-Jan-1990 00:00:00 GMT; path=/; domain=google.com
Set-Cookie: domain=; expires=Mon, 01-Jan-1990 00:00:00 GMT; path=/; domain=google.com
Set-Cookie: expires=; expires=Mon, 01-Jan-1990 00:00:00 GMT; path=/; domain=.google.com
Set-Cookie: path=; expires=Mon, 01-Jan-1990 00:00:00 GMT; path=/; domain=.google.com
Set-Cookie: domain=; expires=Mon, 01-Jan-1990 00:00:00 GMT; path=/; domain=.google.com
Set-Cookie: PREF=ID=3c2e53ffcc387bbb:FF=0:TM=1342766363:LM=1342766364:S=DTuSOuahFqyd6vjp; expires=Sun, 20-Jul-2014 06:39:24 GMT; path=/; domain=.google.com
Set-Cookie: NID=62=HZWk5tBSunVEofFri475wbeCNiChGf_bs7Pz_Z32hfm-B-0M4JRhz-pptjtChOk6lVepLBhOtB2pNHCT5DynobfZaGQaPS5Dh9Rq4YAqt40hExsePHEyA0ECMKjq5KeE; expires=Sat, 19-Jan-2013 06:39:24 GMT; path=/; domain=.google.com; HttpOnly
P3P: CP="This is not a P3P policy! See http://www.google.com/support/accounts/bin/answer.py?hl=en&answer=151657 for more info."
Date: Fri, 20 Jul 2012 06:39:24 GMT
Server: gws
Content-Length: 221
X-XSS-Protection: 1; mode=block
X-Frame-Options: SAMEORIGIN

<HTML><HEAD><meta http-equiv="content-type" content="text/html;charset=utf-8">
<TITLE>302 Moved</TITLE></HEAD><BODY>
<H1>302 Moved</H1>
The document has moved
<A HREF="http://www.google.co.in/">here</A>.
</BODY>
We can see what reply was send by the server. It looks something like Html, well IT IS html. Google.com replied with the content of the page we requested. Quite simple!
Now that we have received our reply, its time to close the socket.
Close socket
Function socket_close is used to close the socket.
1
socket_close($sock);
Thats it.
Lets Revise
So in the above example we learned how to :
1. Create a socket
2. Connect to remote server
3. Send some data
4. Receive a reply
Its useful to know that your web browser also does the same thing when you open www.google.com
This kind of socket activity represents a CLIENT. A client is a system that connects to a remote system to fetch data.
The other kind of socket activity is called a SERVER. A server is a system that uses sockets to receive incoming connections and provide them with data. It is just the opposite of Client. So www.google.com is a server and your web browser is a client. Or more technically www.google.com is a HTTP Server and your web browser is an HTTP client.
Now its time to do some server tasks using sockets. But before we move ahead there are a few side topics that should be covered just incase you need them.
Get IP address of a hostname/domain
When connecting to a remote host , it is necessary to have its IP address. Function gethostbyname is used for this purpose. It takes the domain name as the parameter and returns the ip address.
Quick example
$ip_address = gethostbyname("www.google.com");
// = 173.194.75.104
So the above code can be used to find the ip address of any domain name. Then the ip address can be used to make a connection using a socket.
Server Programming
OK now onto server things. Servers basically do the following :
1. Open a socket
2. Bind to a address(and port).
3. Listen for incoming connections.
4. Accept connections
5. Read/Send
We have already learnt how to open a socket. So the next thing would be to bind it.
Bind a socket
Function bind can be used to bind a socket to a particular address and port. It needs a sockaddr_in structure similar to connect function.
Quick example
if(!($sock = socket_create(AF_INET, SOCK_STREAM, 0)))
{
    $errorcode = socket_last_error();
    $errormsg = socket_strerror($errorcode);
     
    die("Couldn't create socket: [$errorcode] $errormsg \n");
}

echo "Socket created \n";

// Bind the source address
if( !socket_bind($sock, "127.0.0.1" , 5000) )
{
    $errorcode = socket_last_error();
    $errormsg = socket_strerror($errorcode);
     
    die("Could not bind socket : [$errorcode] $errormsg \n");
}

echo "Socket bind OK \n";
Now that bind is done, its time to make the socket listen to connections. We bind a socket to a particular IP address and a certain port number. By doing this we ensure that all incoming data which is directed towards this port number is received by this application.
This makes it obvious that you cannot have 2 sockets bound to the same port. There are exceptions to this rule but we shall look into that in some other article.
Listen for connections
After binding a socket to a port the next thing we need to do is listen for connections. For this we need to put the socket in listening mode. Function socket_listen is used to put the socket in listening mode. Just add the following line after bind.
//listen
socket_listen ($sock , 10)
The second parameter of the function socket_listen is called backlog. It controls the number of incoming connections that are kept "waiting" if the program is already busy. So by specifying 10, it means that if 10 connections are already waiting to be processed, then the 11th connection request shall be rejected. This will be more clear after checking socket_accept.
Now comes the main part of accepting new connections.
Accept connection
Function socket_accept is used for this.


if(!($sock = socket_create(AF_INET, SOCK_STREAM, 0)))
{
    $errorcode = socket_last_error();
    $errormsg = socket_strerror($errorcode);
     
    die("Couldn't create socket: [$errorcode] $errormsg \n");
}

echo "Socket created \n";

// Bind the source address
if( !socket_bind($sock, "127.0.0.1" , 5000) )
{
    $errorcode = socket_last_error();
    $errormsg = socket_strerror($errorcode);
     
    die("Could not bind socket : [$errorcode] $errormsg \n");
}

echo "Socket bind OK \n";

if(!socket_listen ($sock , 10))
{
    $errorcode = socket_last_error();
    $errormsg = socket_strerror($errorcode);
     
    die("Could not listen on socket : [$errorcode] $errormsg \n");
}

echo "Socket listen OK \n";

echo "Waiting for incoming connections... \n";

//Accept incoming connection - This is a blocking call
$client = socket_accept($sock);
     
//display information about the client who is connected
if(socket_getpeername($client , $address , $port))
{
    echo "Client $address : $port is now connected to us.";
}

socket_close($client);
socket_close($sock);
Output
Run the program. It should show
$ php /var/www/server.php
Socket created
Socket bind OK
Socket listen OK
Waiting for incoming connections...
So now this program is waiting for incoming connections on port 5000. Dont close this program , keep it running.
Now a client can connect to it on this port. We shall use the telnet client for testing this. Open a terminal and type
$ telnet localhost 5000
It will immediately show
$ telnet localhost 5000
Trying 127.0.0.1...
Connected to localhost.
Escape character is '^]'.
Connection closed by foreign host.
And the server output will show
Client 127.0.0.1 : 36689 is now connected to us.
So we can see that the client connected to the server. Try the above steps till you get it working perfect.
Note
The socket_getpeername function is used to get details about the client which is connected to the server via a particular socket.
We accepted an incoming connection but closed it immediately. This was not very productive. There are lots of things that can be done after an incoming connection is established. Afterall the connection was established for the purpose of communication. So lets reply to the client.
Function socket_write can be used to write something to the socket of the incoming connection and the client should see it. Here is an example :
if(!($sock = socket_create(AF_INET, SOCK_STREAM, 0)))
{
    $errorcode = socket_last_error();
    $errormsg = socket_strerror($errorcode);
     
    die("Couldn't create socket: [$errorcode] $errormsg \n");
}

echo "Socket created \n";

// Bind the source address
if( !socket_bind($sock, "127.0.0.1" , 5000) )
{
    $errorcode = socket_last_error();
    $errormsg = socket_strerror($errorcode);
     
    die("Could not bind socket : [$errorcode] $errormsg \n");
}

echo "Socket bind OK \n";

if(!socket_listen ($sock , 10))
{
    $errorcode = socket_last_error();
    $errormsg = socket_strerror($errorcode);
     
    die("Could not listen on socket : [$errorcode] $errormsg \n");
}

echo "Socket listen OK \n";

echo "Waiting for incoming connections... \n";

//Accept incoming connection - This is a blocking call
$client =  socket_accept($sock);

//display information about the client who is connected
if(socket_getpeername($client , $address , $port))
{
    echo "Client $address : $port is now connected to us. \n";
}

//read data from the incoming socket
$input = socket_read($client, 1024000);

$response = "OK .. $input";

// Display output  back to client
socket_write($client, $response);
socket_close($client);
Run the above code in 1 terminal. And connect to this server using telnet from another terminal and you should see this :
$ telnet localhost 5000
Trying 127.0.0.1...
Connected to localhost.
Escape character is '^]'.
happy
OK .. happy
Connection closed by foreign host.
So the client(telnet) received a reply from server.
We can see that the connection is closed immediately after that simply because the server program ends after accepting and sending reply. A server like www.google.com is always up to accept incoming connections.
It means that a server is supposed to be running all the time. Afterall its a server meant to serve. So we need to keep our server RUNNING non-stop. The simplest way to do this is to put the accept in a loop so that it can receive incoming connections all the time.
Live Server
So a live server will be alive always. Lets code this up

if(!($sock = socket_create(AF_INET, SOCK_STREAM, 0)))
{
    $errorcode = socket_last_error();
    $errormsg = socket_strerror($errorcode);
     
    die("Couldn't create socket: [$errorcode] $errormsg \n");
}

echo "Socket created \n";

// Bind the source address
if( !socket_bind($sock, "127.0.0.1" , 5000) )
{
    $errorcode = socket_last_error();
    $errormsg = socket_strerror($errorcode);
     
    die("Could not bind socket : [$errorcode] $errormsg \n");
}

echo "Socket bind OK \n";

if(!socket_listen ($sock , 10))
{
    $errorcode = socket_last_error();
    $errormsg = socket_strerror($errorcode);
     
    die("Could not listen on socket : [$errorcode] $errormsg \n");
}

echo "Socket listen OK \n";

echo "Waiting for incoming connections... \n";

//start loop to listen for incoming connections
while (true)
{
    //Accept incoming connection - This is a blocking call
    $client =  socket_accept($sock);
     
    //display information about the client who is connected
    if(socket_getpeername($client , $address , $port))
    {
        echo "Client $address : $port is now connected to us. \n";
    }
     
    //read data from the incoming socket
    $input = socket_read($client, 1024000);
     
    $response = "OK .. $input";
     
    // Display output  back to client
    socket_write($client, $response);
}
We havent done a lot there. Just put the socket_accept in a loop.
Now run the server program in 1 terminal , and open 3 other terminals.
From each of the 3 terminal do a telnet to the server port.
Each of the telnet terminal would show :
$ telnet localhost 5000
Trying 127.0.0.1...
Connected to localhost.
Escape character is '^]'.
happy
OK .. happy
Connection closed by foreign host.
And the server terminal would show
$ php /var/www/server.php
Socket created
Socket bind OK
Socket listen OK
Waiting for incoming connections...
Client 127.0.0.1 : 37119 is now connected to us.
Client 127.0.0.1 : 37122 is now connected to us.
Client 127.0.0.1 : 37123 is now connected to us.
So now the server is running nonstop and the telnet terminals are also connected nonstop. Now close the server program. All telnet terminals would show "Connection closed by foreign host."
Good so far. But still there is not effective communication between the server and the client. The server program accepts connections in a loop and just send them a reply, after that it does nothing with them. Also it is not able to handle more than 1 connection at a time. So now its time to handle the connections , and handle multiple connections together.
Handling Connections
To handle every connection we need a separate handling code to run along with the main server accepting connections. One way to achieve this is using threads. The main server program accepts a connection and creates a new thread to handle communication for the connection, and then the server goes back to accept more connections.
However php does not support threading directly.
Another method is to use the select function. The select function basically 'polls' or observers a set of sockets for certain events like if its readable, or writable or had a problem or not etc.
So the select function can be used to monitor multiple clients and check which client has send a message.
Quick Example
error_reporting(~E_NOTICE);
set_time_limit (0);

$address = "0.0.0.0";
$port = 5000;
$max_clients = 10;

if(!($sock = socket_create(AF_INET, SOCK_STREAM, 0)))
{
    $errorcode = socket_last_error();
    $errormsg = socket_strerror($errorcode);
     
    die("Couldn't create socket: [$errorcode] $errormsg \n");
}

echo "Socket created \n";

// Bind the source address
if( !socket_bind($sock, $address , 5000) )
{
    $errorcode = socket_last_error();
    $errormsg = socket_strerror($errorcode);
     
    die("Could not bind socket : [$errorcode] $errormsg \n");
}

echo "Socket bind OK \n";

if(!socket_listen ($sock , 10))
{
    $errorcode = socket_last_error();
    $errormsg = socket_strerror($errorcode);
     
    die("Could not listen on socket : [$errorcode] $errormsg \n");
}

echo "Socket listen OK \n";

echo "Waiting for incoming connections... \n";

//array of client sockets
$client_socks = array();

//array of sockets to read
$read = array();

//start loop to listen for incoming connections and process existing connections
while (true)
{
    //prepare array of readable client sockets
    $read = array();
     
    //first socket is the master socket
    $read[0] = $sock;
     
    //now add the existing client sockets
    for ($i = 0; $i < $max_clients; $i++)
    {
        if($client_socks[$i] != null)
        {
            $read[$i+1] = $client_socks[$i];
        }
    }
     
    //now call select - blocking call
    if(socket_select($read , $write , $except , null) === false)
    {
        $errorcode = socket_last_error();
        $errormsg = socket_strerror($errorcode);
     
        die("Could not listen on socket : [$errorcode] $errormsg \n");
    }
     
    //if ready contains the master socket, then a new connection has come in
    if (in_array($sock, $read))
    {
        for ($i = 0; $i < $max_clients; $i++)
        {
            if ($client_socks[$i] == null)
            {
                $client_socks[$i] = socket_accept($sock);
                 
                //display information about the client who is connected
                if(socket_getpeername($client_socks[$i], $address, $port))
                {
                    echo "Client $address : $port is now connected to us. \n";
                }
                 
                //Send Welcome message to client
                $message = "Welcome to php socket server version 1.0 \n";
                $message .= "Enter a message and press enter, and i shall reply back \n";
                socket_write($client_socks[$i] , $message);
                break;
            }
        }
    }

    //check each client if they send any data
    for ($i = 0; $i < $max_clients; $i++)
    {
        if (in_array($client_socks[$i] , $read))
        {
            $input = socket_read($client_socks[$i] , 1024);
             
            if ($input == null)
            {
                //zero length string meaning disconnected, remove and close the socket
                unset($client_socks[$i]);
                socket_close($client_socks[$i]);
            }

            $n = trim($input);

            $output = "OK ... $input";
             
            echo "Sending output to client \n";
             
            //send response to client
            socket_write($client_socks[$i] , $output);
        }
    }
}
Run the above server and open 3 terminals like before. Now the server will create a thread for each client connecting to it.
The telnet terminals would show :
$ telnet localhost 5000
Trying 127.0.0.1...
Connected to 127.0.0.1.
Escape character is '^]'.
Welcome to php socket server version 1.0
Enter a message and press enter, and i shall reply back
hello
OK ... hello
how are you
OK ... how are you
The server terminal might look like this
$ php /var/www/server.php
Socket created
Socket bind OK
Socket listen OK
Waiting for incoming connections...
Client 127.0.0.1 : 36259 is now connected to us.
Sending output to client
Sending output to client
Client 127.0.0.1 : 36274 is now connected to us.
Sending output to client
Sending output to client
Client 127.0.0.1 : 36276 is now connected to us.
Sending output to client
Sending output to client
The above connection handler takes some input from the client and replies back with the same. Simple! Here is how the telnet output might look
So now we have a server thats communicative. Thats useful now.

Socket Programming in PHP

Introduction

Sockets are used for interprocess communication. Interprocess communication is generally based on client-server model. In this case, client-server are the applications that interact with each other. Interaction between client and server requires a connection. Socket programming is responsible for establishing that connection between applications to interact.
By the end of this tip, we will learn how to create a simple client-server in PHP. We will also learn how client application sends message to server and receives it from the same.

Using the Code

Aim: Develop a client to send a string message to server and server to return reverse of the same message to client.

PHP SERVER

Step 1: Set variables such as "host" and "port"

$host = "127.0.0.1";
$port = 5353;
// No Timeout 
set_time_limit(0);

Port number can be any positive integer between 1024 -65535.

Step 2: Create Socket

$socket = socket_create(AF_INET, SOCK_STREAM, 0) or die("Could not create socket\n");

Step 3: Bind the socket to port and host

Here the created socket resource is bound to IP address and port number.
$result = socket_bind($socket, $host, $port) or die("Could not bind to socket\n");

Step 4: Start listening to the socket

After getting bound with IP and port server waits for the client to connect. Till then it keeps on waiting.
$result = socket_listen($socket, 3) or die("Could not set up socket listener\n");

Step 5: Accept incoming connection

This function accepts incoming connection request on the created socket. After accepting the connection from client socket, this function returns another socket resource that is actually responsible for communication with the corresponding client socket. Here “$spawn” is that socket resource which is responsible for communication with client socket.
$spawn = socket_accept($socket) or die("Could not accept incoming connection\n");


So far, we have prepared our server socket but the script doesn't actually do anything. Keeping to our aforesaid aim, we will read message from client socket and then send back reverse of the received message to the client socket again.

Step 6: Read the message from the Client socket

$input = socket_read($spawn, 1024) or die("Could not read input\n");

Step 7: Reverse the message

$output = strrev($input) . "\n";

Step 8: Send message to the client socket

socket_write($spawn, $output, strlen ($output)) or die("Could not write output\n"); 

Close the socket

socket_close($spawn);
socket_close($socket);
This completes with the server. Now we will learn to create PHP client.

PHP CLIENT

The first two steps are the same as in the server.

Step 1: Set variables such as "host" and "port"

$host = "127.0.0.1";
$port = 5353;
// No Timeout 
set_time_limit(0);

Note: Here the port and host should be same as defined in server.

Step 2: Create Socket

$socket = socket_create(AF_INET, SOCK_STREAM, 0) or die("Could not create socket\n");

Step 3: Connect to the server

$result = socket_connect($socket, $host, $port) or die("Could not connect toserver\n");
Here unlike server, client socket is not bound with port and host. Instead it connects to server socket, waiting to accept the connection from client socket. Connection of client socket to server socket is established in this step.

Step 4: Write to server socket

socket_write($socket, $message, strlen($message)) or die("Could not send data to server\n");
In this step, client socket data is sent to the server socket.

Step 5: Read the response from the server

$result = socket_read ($socket, 1024) or die("Could not read server response\n");
echo "Reply From Server  :".$result;

Step 6: Close the socket

socket_close($socket);

Complete Code

SERVER (server.php)

// set some variables
$host = "127.0.0.1";
$port = 25003;
// don't timeout!
set_time_limit(0);
// create socket
$socket = socket_create(AF_INET, SOCK_STREAM, 0) or die("Could not create socket\n");
// bind socket to port
$result = socket_bind($socket, $host, $port) or die("Could not bind to socket\n");
// start listening for connections
$result = socket_listen($socket, 3) or die("Could not set up socket listener\n");

// accept incoming connections
// spawn another socket to handle communication
$spawn = socket_accept($socket) or die("Could not accept incoming connection\n");
// read client input
$input = socket_read($spawn, 1024) or die("Could not read input\n");
// clean up input string
$input = trim($input);
echo "Client Message : ".$input;
// reverse client input and send back
$output = strrev($input) . "\n";
socket_write($spawn, $output, strlen ($output)) or die("Could not write output\n");
// close sockets
socket_close($spawn);
socket_close($socket);

CLIENT (client.php)

$host    = "127.0.0.1";
$port    = 25003;
$message = "Hello Server";
echo "Message To server :".$message;
// create socket
$socket = socket_create(AF_INET, SOCK_STREAM, 0) or die("Could not create socket\n");
// connect to server
$result = socket_connect($socket, $host, $port) or die("Could not connect to server\n");  
// send string to server
socket_write($socket, $message, strlen($message)) or die("Could not send data to server\n");
// get server response
$result = socket_read ($socket, 1024) or die("Could not read server response\n");
echo "Reply From Server  :".$result;
// close socket
socket_close($socket);

After creating the above files (server.php and client.php), do as follows:
  1. Copy these files in www directory (in case of WAMP), located at C:\wamp.
  2. Open your web browser and type localhost in the address bar.
  3. Browse server.php first followed by client.php.



Saturday, 17 August 2013

Top AJAX interview questions and answers


Questions : What is Ajax ?
Answers : Ajax is nothing but acronym for Asynchronous JavaScript and xml , It is not a new technology even it is not a technology but use to enhance web technology , In 2005 Google developer need to more fast search engine so they suggested to use Ajax . in older days When we need to send / fetch data to / from server page was reload every time hence take more time , use more memory , but being use AJAX no need to reload page again and again for sending small amount of data to server through Ajax we utilize more memory and bandwidth and our website work faster and fastest , also able to move and use fetched data , Ajax is used on client site means with java script and html
 
Questions : What is advantage of Ajax
Answers :  Basic advantage of Ajax is Bandwidth utilization means when we have more type of data on same page or use more included page , hence data is fetched without loading the page it's save memory also it is more interactive no any user want lose their information from that page , so the concentrate only on same page fastest where loading a page is difficult or more time consuming Ajax do best work So why in all modern website need concentration to use Ajax ,it is a Browser technology independent of web server software .

Like every thing advantage and disadvantage Ajax has too some disadvantage like

When we use Ajax it is difficult to return back page , when we click on back button we

Got first page(because same page is using for sending or fetching data but when we need just last use thing we could not able to seen last modified data they gone to starting point

And also need to more concentration because it is faster to implement but still it is very beneficial to us
 
Questions : How AJAX Work ?
Answer : How it work means it use with JavaScript , hence java script can communicate directly with the server by using the JavaScript XMLHttpRequest Object using this object JavaScript fetch and send data without reloading the page .

Following key word used with Ajax though JavaScript ;
1.XMLHttpRequest create object for browser like Firebox ,Muzilla, opera ,safari and other .

2>Internet explore use ActiveXObject
3>onreadystatechange henceActiveXObjectvar. readyState ==4 means response is ready to send and sent by server hence process complete there values like 1,2 ,3 means ,initialize ,in process etc ..
4.>object .status== 200 means status is ok other wise produce error404

5> for open a file or data use

Object. open("GET","file.php",true)
 


Questions : Which two methods are used for handling Cross-Domain Ajax Calls ?
Answer : Cross-domain means the ability to manually or automatically access or transfer data between two or more differing security domain
1) CROS (Cross-Origin Resource Sharing) : Works with all HTTP verbs and Mos modern web browsers. Provides better support for error handling than JSONP.
2) JSONP (JSON with padding) : It is only works HTTP GET verb and on legacy browsers.
 
Questions : What are the disadvantages of AJAX?
Answer : These are the disadvantages:
1) AJAX is dependent on Javascript. If there is some Javascript problem with the browser or in the OS,your AJAX functionality may not work.
2) Search engines generally do not index Javascript present in web pages. AJAX can be problematic in Search engines as it uses Javascript for most of its parts.
3) source code written for AJAX is easily human readable.
4) Debugging is difficult. We have often to use additional Javascript code for that.
5) Data of all requests is URL-encoded. It increases the size of the request. It can cause problem while Paginating through GridView if there is a huge data.
6)Slow and unreliable network connection.
7)Problem with browser back button when using AJAX enabled pages.
 

Friday, 16 August 2013

How to make Custom radio button and check boxes via css?

css

label {
display: inline-block;
cursor: pointer;
position: relative;
padding-left: 25px;
margin-right: 15px;
font-size: 13px;
}
.wrapper {
width: 500px;
margin: 50px auto;
}
input[type=radio],
input[type=checkbox] {
display: none;
}
label:before {
content: "";
display: inline-block;

width: 16px;
height: 16px;

margin-right: 10px;
position: absolute;
left: 0;
bottom: 1px;
background-color: #aaa;
box-shadow: inset 0px 2px 3px 0px rgba(0, 0, 0, .3), 0px 1px 0px 0px rgba(255, 255, 255, .8);
}

.radio label:before {
border-radius: 8px;
}
.checkbox label {
margin-bottom: 10px;
}
.checkbox label:before {
    border-radius: 3px;
}

input[type=radio]:checked + label:before {
    content: "\2022";
    color: #f3f3f3;
    font-size: 30px;
    text-align: center;
    line-height: 18px;
}

input[type=checkbox]:checked + label:before {
content: "\2713";
text-shadow: 1px 1px 1px rgba(0, 0, 0, .2);
font-size: 15px;
color: #f3f3f3;
text-align: center;
    line-height: 15px;
}


HTML
<div class="wrapper">
<h3>Radio Button</h3>
<div class="radio">
<input id="male" type="radio" name="gender" value="male">
<label for="male">Male</label>
<input id="female" type="radio" name="gender" value="female">
<label for="female">Female</label>
</div>

<h3>Checkbox</h3>
<div class="checkbox">
<input id="check1" type="checkbox" name="check" value="check1">
<label for="check1">Checkbox No. 1</label>
<br>
<input id="check2" type="checkbox" name="check" value="check2">
<label for="check2">Checkbox No. 2</label>
</div>
</div>
               OUTPUT
                                 

What is the difference between HTML vs XHTML vs DHTML?

HTML:  HTML (HyperText Markup Language): HTML is the most widely accepted language used to build websites. It is the main structure of a website. It builds tables, creates divisions, gives a heading message (In the title bar of programs), and actually outputs text.

XHTML (eXtensible HyperText Markup Language): : XHTML is extremely similar but follows the rules of XML. The main differences between HTML and XHTML are the case-sensitivity, the need to use closing tags for all tags, the need to use quotes around all attribute values and that all attributes must be in lowercase as XML requires. Special characters between tags need to be replaced with its code equivalent. Declaring the correct doctype (first line in source code) and language (in meta tag in the head of the source code) is required.

XHTML is used to be compatible with XML programming. Following the rules now would make it possible to include XML programming in the future. It is not difficult to change HTML pages to XHTML, but it can be time-consuming. Finding all line breaks and images to include closing tags, converting any uppercase to lowercase and any other incompatibility can be a nuisance. Using a find and replace program can allow you to edit your code faster, but you still have to reupload all those changes. It is recommended that programmers try to remember these rules to comply with W3C recommendations, so the web pages appear correctly in most browsers.

When should you be concerned with XHTML instead of just plain HTML? If the website will contain a catalog of items as in an ecommerce site, the site accesses a database, the site accesses information from another source that uses a different programming language or the site is expected to grow and exist for many years. XHTML is used when referring to XML files used for RSS feeds, some music players, some image galleries and many more applications.

XHTML is popular for mobile web design when used with proper CSS code. Try viewing your website in a mobile simulator to see how your website looks. If you want mobile phones like Nokia or iPhone to access your website, you should use XHTML. You may need to change your DOCTYPE, but if you do, you may need to change additional code. Try to avoid JavaScript, large files, large images and tables.

XHTML  is the same as HTML, except it has a cleaner syntax. XHTML uses the same tags as HTML, so people who know HTML know messy XHTML.

Some new rules are followed in XHTML like:

  • XHTML elements must be properly nested.
  • XHTML elements must always be closed.
  • XHTML elements must be in lowercase.
  • XHTML documents must have one root element.
  • In HTML, some elements can be improperly nested within each other, like this:
                 <b><i>This text is bold and italic</b></i>
  • In XHTML, all elements must be properly nested within each other, like this:
                <b><i>This text is bold and italic</i></b>

DHTML(Dynamic HyperText Markup Language): is a combination of different technologies to make your HTML interactive. Common languages used are HTML (of course), Javascript and Stylesheets. is not a language, but the art of using HTML, JavaScript, DOM and CSS together to create dynamic things, such as navigation menus.

How to flip any image via using css?

css
img{
        -moz-transform: scaleX(-1);
        -o-transform: scaleX(-1);
        -webkit-transform: scaleX(-1);
        transform: scaleX(-1);
        filter: FlipH;
        -ms-filter: "FlipH";
}

image before





image after