Wednesday, December 25, 2013

Java exercise - Client and Server example IV, with option to request Read Temperature

Continue on last exercise of Java Client-Server exercise, with the function of reading system temperature in Raspberry Pi. The host.java and client.java are modified to handle option parameter passed in Client-Server Socket communication, such that host can response with temperature if requested.

Java Client-Server Socket communication, with option of reading Raspberry Pi's system temperature.
Java Client-Server Socket communication, with option of reading Raspberry Pi's system temperature.
Request to read temperature (RQS_TEMP) is hard coded in client side, client.java
import java.net.Socket;
import java.io.InputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.PrintWriter;
import java.net.UnknownHostException;

class client{
    
    final static Integer RQS_DEFAULT = 0;
    final static Integer RQS_TEMP = 1;

    public static void main(String args[])
    { 
        if(args.length == 0){
            System.out.println("usage: java client <port>");
            System.exit(1);
        }
        
        int port = isParseInt(args[0]);
        if(port == -1){
            System.out.println("usage: java client <port>");
            System.out.println("<port>: integer");
            System.exit(1);
        }
        
        try{
            //IP is hard coded
            //port is user entry
            Socket socket = new Socket("192.168.111.109", port);
            
            PrintWriter printWriter = 
                new PrintWriter(socket.getOutputStream(), true);
            printWriter.println(RQS_TEMP);
            
            InputStream inputStream = socket.getInputStream();
            
            ByteArrayOutputStream byteArrayOutputStream = 
                new ByteArrayOutputStream(1024);
            byte[] buffer = new byte[1024];

            int bytesRead;
            while ((bytesRead = inputStream.read(buffer)) != -1){
                byteArrayOutputStream.write(buffer, 0, bytesRead);
            }
                
            socket.close();
        
            System.out.println(byteArrayOutputStream.toString("UTF-8"));
            
        }catch(UnknownHostException e){
            System.out.println(e.toString());
        }catch(IOException e){
            System.out.println(e.toString());
        }

    }


    private static int isParseInt(String str){
        
        int num = -1;
        try{
             num = Integer.parseInt(str);
        } catch (NumberFormatException e) {
        }
        
        return num;
    }
    
}

host.java
import java.io.IOException;
import java.io.OutputStream;
import java.io.PrintStream;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.InputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.logging.Level;
import java.util.logging.Logger;

public class host {
    
    final static Integer RQS_DEFAULT = 0;
    final static Integer RQS_TEMP = 1;

    public static void main(String srgs[]) {

        int count = 0;

        //hard code to use port 8080
        try (ServerSocket serverSocket = new ServerSocket(8080)) {
            
            System.out.println("I'm waiting here: " + serverSocket.getLocalPort());
            
            while (true) {
                
                try {
                    Socket socket = serverSocket.accept();
                            
                    count++;
                    System.out.println("#" + count + " from "
                            + socket.getInetAddress() + ":" 
                            + socket.getPort());
                    
                    HostThread myHostThread = new HostThread(socket, count);
                    myHostThread.start();
                    
                } catch (IOException ex) {
                    System.out.println(ex.toString());
                }
            }
        } catch (IOException ex) {
            System.out.println(ex.toString());
        }
    }
    
    private static class HostThread extends Thread{
        
        private Socket hostThreadSocket;
        int cnt;
        
        HostThread(Socket socket, int c){
            hostThreadSocket = socket;
            cnt = c;
        }

        @Override
        public void run() {
            //
            Integer rqs = RQS_DEFAULT;
            try{
                BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(hostThreadSocket.getInputStream()));
                rqs =  new Integer(bufferedReader.readLine());
            }catch (IOException ex){
                Logger.getLogger(host.class.getName()).log(Level.SEVERE, null, ex);
            }
            
            System.out.println("RQS = " + rqs);
            //
            
            String returnMsg;
            if(rqs.equals(RQS_DEFAULT)){
                returnMsg = "Hello from Raspberry Pi in background thread, you are #" + cnt;
            }else if(rqs.equals(RQS_TEMP)){
                returnMsg = ReadTemp() + "you are #" + cnt;
            }else{
                returnMsg = "unknown RQS! you are #" + cnt;
            }

            OutputStream outputStream;
            try {
                outputStream = hostThreadSocket.getOutputStream();
                
                try (PrintStream printStream = new PrintStream(outputStream)) {
                        printStream.print(returnMsg);
                }
            } catch (IOException ex) {
                Logger.getLogger(host.class.getName()).log(Level.SEVERE, null, ex);
            }finally{
                try {
                    hostThreadSocket.close();
                } catch (IOException ex) {
                    Logger.getLogger(host.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
        }
    }
    
    private static String ReadTemp(){
        String Temp = null;
        
        String[] command = {"vcgencmd", "measure_temp"};
        StringBuilder cmdReturn = new StringBuilder();
        try {
            ProcessBuilder processBuilder = new ProcessBuilder(command);
            Process process = processBuilder.start();
            
            try (InputStream inputStream = process.getInputStream()) {
                int c;
                while ((c = inputStream.read()) != -1) {
                    cmdReturn.append((char) c);
                }
            }
            
            Temp = cmdReturn.toString();

        } catch (IOException ex) {
            System.out.println(ex.toString());
        }
        
        return Temp;
    }
}



Download source code.



Java exercise - Implement client and server to communicate using Socket, step-by-step.

No comments: