Tuesday, February 28, 2017

Count Server Socket

Definition: Program to demonstrate use of Page views count on server.
Count server program will increment page view counter for every client request.

Count Server Socket Program

import java.io.*;
import java.net.*;

public class CountServer {

    public static void main(String[] args) throws IOException {

        ServerSocket ss = new ServerSocket(1234);
        Socket cs = null;
        System.out.println("Waiting for connection.....");
        int count=0;
        while(true){
            cs = ss.accept();          
            count++;
            System.out.println("Total visitors:"+count);
            cs.close();
        }
        //ss.close();
    }
}

Output on Server screen

Waiting for connection.....
Total visitors:1

//Validations and exception handling to be added.

Count Client Socket Program

/* This program will just create socket with server. Note: try-catch clauses are not added to keep logic simple…*/

import java.io.*;
import java.net.*;

public class CountClient
{
   public static void main(String[] args) throws IOException
   {
         Socket s1 = new Socket("localhost", 1234);
         System.out.println("Hello");
         s1.close();
   }
}

Output on Client screen

Hello

No comments:

Post a Comment