G&G Inc's Client Server Java Page

Keywords: Client Server java training

Back to G&G Inc's home page.
Back to G&G Inc's Java page.
Check out G&G Inc's training page.

KISS - Keep It Sweet and Simple

Client and Server Code

Notes:
Two first two client and server programs, show the basic idea of two programs talking to each other over a socket. The client program read in a number from the keyboard, sends it to the server program, which computes the square of the number and returns it to the client who prints it out.
The second pair of programs build on the first two, to allow the client to send a file to the server, the converse "get a file" part is not implemented. These programs are specifically designed with one criterion in mind: be really short so they can be cut and pasted into a file on your own system. Lots of things are hard coded that in a more robust world would be setup in an user interface dialog. Even though the program is a file transfer program, is has nothing to do with the well known "ftp" protocol.

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

public class SimpleClassClient {

   // you MUST change this address to the real IP address 
   // where your SimpleClassServer program is running
   public static final String IPADDR = "10.0.0.20";   
   public static final int PORT = 5002;

   public static void main(String args[]) {

   Socket s;
   InputStream in             = null; 
   OutputStream out           = null;
   BufferedReader din         = null;
   PrintWriter dout           = null;
 
      try {

         s = new Socket(IPADDR, PORT);
         in = s.getInputStream();
         out = s.getOutputStream();  
         dout = new PrintWriter(out);
         InputStreamReader isr = new InputStreamReader(in);
         din = new BufferedReader(isr);
      }
      catch (IOException e) {
         System.out.println("failed. Server may be down.");
         System.out.println(e.toString());
      }


      String line;
      BufferedReader stdin
         = new BufferedReader(new InputStreamReader(System.in));

      while(true) {
 
         try 
         {
             System.out.println(" Input an Integer ");
             String input;
             input = stdin.readLine();
             dout.println(input);
             dout.flush();
             line = din.readLine();
         }
         catch (IOException e) 
         { 
             System.out.println(e.toString());
             line = null;
         }
      if (line == null) {
            System.out.println("Connection lost.. Server may be down. \n");
             break;
         } else {
            System.out.println(line);         
         }        
      }
   }
}

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

public class SimpleClassServer {

   public final static int PORT = 5002;

   public static void main(String argv[]) { 

      ServerSocket listen_socket = null;
      Socket client_socket       = null;
      InputStream in             = null;
      OutputStream out           = null;
      BufferedReader din         = null;
      PrintWriter dout           = null;

      while(true) {
          try { listen_socket = new ServerSocket(PORT); }
          catch (IOException e) 
             {System.out.println(" Server " +e+
              "\nException creating server socket");}
          try { client_socket = listen_socket.accept(); }
          catch (IOException e) 
             {System.out.println(" Server: " +e+
              "\nException creating listen-socket");}
          System.out.println(" Server: Socket accepted ");
          try { 
             in = client_socket.getInputStream();
             out = client_socket.getOutputStream();
             dout = new PrintWriter(out);
             InputStreamReader isr = new InputStreamReader(in);
             din = new BufferedReader(isr);
          }
          catch (IOException e) {
             try {client_socket.close();} catch (IOException e2) {} ;
             System.err.println("Exception while getting socket: " + e);
             continue;
          }
          String str;
          try {str = din.readLine();}
          catch (IOException e)
             {System.out.println(" Server: I/O error " + e); 
             str = null;}
          while(str != null) {  
              int n = 0;
              try {n = Integer.parseInt(str);}
              catch (NumberFormatException ne) 
                 {System.out.println(" Server: found non-numeric: " + str);}
              // simply send back the square of the number the client sent
              n = n * n;
              System.out.println("sending back: " + n);
              dout.println(Integer.toString(n));
              dout.flush();
              try {str = din.readLine();}
              catch (IOException e)
                 {str = null;}
           }
            try {client_socket.close();
                listen_socket.close();}
            catch (IOException e)
                {System.out.println(" Server:  I/O close error " + e);}
            System.out.println(" Server: Socket closed ");
       }
   }
}

package biz.gginc;

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

public class KissFTPClient {

	static final int      PORT     = 5002;
	static final String   IPADDR   = "localhost" ; 
	static final String   SRC_DIR  = "C:\\source\\" ; 
    static final String   DEST_DIR = "C:\\target\\" ;     
    static BufferedReader din      = null;
    static OutputStream   out      = null;

    public static void main(String args[]) {

        Socket s;
        InputStream in             = null; 

        String line = "";
        BufferedReader stdin
        = new BufferedReader(new InputStreamReader(System.in));

        try {
            s = new Socket(IPADDR, PORT);
            in = s.getInputStream();
            out = s.getOutputStream();  
            InputStreamReader isr = new InputStreamReader(in);
            din = new BufferedReader(isr);
        }
        catch (IOException e) {
            System.out.println("failed. Server may be down.");
            System.out.println(e.toString());
        }

        while(true) {

            try 
            {
                System.out.println(" put/get/quit ");
                String input;
                input = stdin.readLine().trim();
                //System.out.println(" Input " + input);
                if(input.startsWith("quit")) break;
                if(input.startsWith("put")) {
                    doPut(input, stdin, din);
                } else if(input.startsWith("get")) {
                    doGet(stdin, din);
                } else {
                    System.out.println(" Input error ");
                    continue;
                }
            }
            catch (IOException e) 
            { 
                System.out.println(e.toString());
                line = null;
            }

            if (line == null) {
                System.out.println("Connection lost.. Server may be down. \n");
                break;
            } else {
                System.out.println(line);         
            }        
        }
    }


    private static void doGet(BufferedReader stdin, BufferedReader din) throws IOException {
        System.out.println(" get not implemented on server ");
    }

    private static void doPut(String in, BufferedReader stdin, BufferedReader din ) throws IOException {

        String input;
        if(in.length() > 3) {
            input = in.substring(3).trim();
        } else {
            System.out.println(" Filename to put: ");
            input = stdin.readLine().trim();
        }
        String inputd = SRC_DIR + input;

        // read lots of bytes from newly opened file input, and write to out
        byte[] buffer = new byte[1024*8];
        int total = 0;
        int nRead = 0;
        FileInputStream inputStream = new FileInputStream(inputd);
        BufferedOutputStream bout = new BufferedOutputStream(out);
        bout.write((input + "**PUT**").getBytes());
        bout.flush();
        
        // send over file name
        System.out.print(" reading ");
        while((nRead = inputStream.read(buffer)) != -1) {
            total += nRead;
            bout.write(buffer, 0, nRead);
            //System.out.print("\r reading " + nRead + " bytes");
        }
        bout.write(("**EOF**").getBytes());
        bout.flush();
        inputStream.close();    
        System.out.print("\r read " + total + " bytes");

    }

}

package biz.gginc;

import java.net.*;
import java.io.*;
//import java.util.*;

public class KissFTPServer 
{
    final static int    PORT     = 5002;
    static final String SRC_DIR  = "C:\\source\\" ; 
    static final String DEST_DIR = "C:\\target\\" ; 

    public static void main(String argv[]) { 

        ServerSocket listen_socket = null;
        Socket client_socket       = null;
        InputStream in             = null;
        OutputStream out           = null;
        PrintWriter dout           = null;

        while(true) {
            try { listen_socket = new ServerSocket(PORT); }
            catch (IOException e) 
            {System.out.println(" Server " +e+
                    "\nException creating server socket");}
            try { client_socket = listen_socket.accept(); }
            catch (IOException e) 
            {System.out.println(" Server: " +e+
                    "\nException creating listen-socket");}
            System.out.println(" Server: Socket accepted ");
            try { 
                in = client_socket.getInputStream();
                out = client_socket.getOutputStream();
                dout = new PrintWriter(out);
            }
            catch (IOException e) {
                try {client_socket.close();} catch (IOException e2) {} ;
                System.err.println("Server: Exception while getting socket: " + e);
                continue;
            }


            String str = "";
            while (str != null) {
                String filename = "";
                String firstpart = "";
                try {
                    byte[] buffer = new byte[128];
                    int size = in.read(buffer, 0 , 128);
                    str = new String(buffer, 0, size);
                    System.out.println(" Server input " + new String(buffer));
                    int indexend = str.indexOf("**PUT**");
                    if(indexend < 0) indexend = str.indexOf("**GET**");
                    filename = DEST_DIR + str.substring(0,indexend).trim();
                    firstpart = str.substring(indexend+7);
                }
                catch (IOException e)
                {
                    System.out.println(" Server: I/O error " + e); 
                    str = null;
                }

                String status = "?";
                try {
                    if(str.indexOf("**PUT**") > 0) {
                        doReceive( in, filename, firstpart);
                        status = " Done.";
                    } else if(str.indexOf("**GET**") > 0) {
                        doSend(out, filename);
                        status = " Not Implemented.";
                    } else {
                        System.out.println(" Input error " + str);
                        continue;
                    }

                    dout.println(status);
                    dout.flush();
                    str = "";
                }
                catch (IOException e)
                {System.out.println(" Server: I/O error " + e); 
                str = null;}
            }


            try {
                client_socket.close();
                listen_socket.close();
            }
            catch (IOException e)
            {
                System.out.println(" Server:  I/O close error " + e);
            }    
            System.out.println(" Server: Sockets closed ");
        }
    }

    private static void doSend(OutputStream out, String fname) throws IOException {
        System.out.println(" get not implemented on server " + fname);
    }

    private static void doReceive(InputStream in, String fname, String firstpart) throws IOException {
        //System.out.println(" put called " + fname);  //  on this side means receive a file
        // read lots of bytes from din, and write to newly opened file fname

        byte[] buffer = new byte[1024*8];
        int len = firstpart.length();
        int total = len;
        int nRead = len;
        FileOutputStream os = new FileOutputStream(fname);

        if(len > 0) {
            os.write(firstpart.getBytes(), 0, len);
        }

        //System.out.print(" writing ");
        boolean eof = false;
        while((!eof && (nRead = in.read(buffer, 0, 1024*8)) > 0)) {
            // check for end
            String instr = new String(buffer, 0, nRead);
            if(instr.endsWith("**EOF**")) {
                nRead = nRead - 7;
                eof = true;
            }
            total += nRead;
            os.write(buffer, 0, nRead);
        }
        System.out.println(" wrote " + total + " bytes");

        os.flush();
        os.close();

    }
}

Questions? Comments? Send a note to G&G Inc.

Google
 

Garnatz and Grovender, Inc.
17 South 1st St. Apt A1202
Minneapolis, Minnesota 55401-1831 USA

e-mail: philg@gginc.biz
URL: http://www.gginc.biz

Copyright © 1995, 2017 Garnatz and Grovender, Inc.