1

I'm very new to Java here. I have a program which acts like a calculator between client and server. the client will enter their function like this (+ 1 2). But now Im giving it a GUI interface. How do i pass the user input from GUI to client console then pass it to the server to calculate and then displaying it back to the UI? i just need something simple.

client

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

import java.awt.*;        // using AWT containers and components
import java.awt.event.*;  // using AWT events and listener interfaces
import javax.swing.*;

public class mathClient extends JFrame implements ActionListener {
    private int count = 0;
    private JFrame frame;
    private JPanel panel;

    private JLabel lblInput;
    private JLabel lblOutput;
    private JTextField tfInput;
    private JTextField tfOutput;


            /** The entry main() method */
    public static void main(String[] args) throws Exception {
    // Invoke the constructor to setup the GUI, by allocating an instance
        mathClient app = new mathClient();

    }

            public void actionPerformed(ActionEvent event){
                try{
                Socket clientSocket = new Socket("localhost", 50000);
                BufferedReader inFromServer = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
                DataOutputStream outToServer = new DataOutputStream(clientSocket.getOutputStream());
                PrintWriter print = new PrintWriter(clientSocket.getOutputStream(), true);

                String input;
                String output;

                //String input;

                while(true){
                    //System.out.println("Please enter your function and numbers:");
                    input = tfInput.getText();

                    print.println(input);

                    if(input.equals("disconnect")){
                        break;
                    }   

                    output = inFromServer.readLine();
                    System.out.println(output);
                    tfOutput.setText(output);


                }
                clientSocket.close();
                }
                catch (Exception e)
                {
                }


        }


    public mathClient()
    {
        Container contentPane = getContentPane();
        contentPane.setLayout(new BorderLayout());

        JFrame frame = new JFrame("Calculator");
        JPanel panel = new JPanel();

        JLabel lblInput = new JLabel("Input: ");

        JLabel lblOutput = new JLabel("Output: ");    

        JTextField tfInput = new JTextField();
        tfInput.setEditable(true);
    //  tfInput.addActionListener();

        JTextField tfOutput = new JTextField();
        tfOutput.setEditable(false);

        JButton btnCalculate = new JButton("Calculate");
        btnCalculate.addActionListener(this);

        frame.add(panel);
        panel.add(lblInput);
        panel.add(tfInput);
        panel.add(lblOutput);
        panel.add(tfOutput);
        panel.add(btnCalculate);

        tfInput.setPreferredSize(new Dimension(200, 30));
        tfOutput.setPreferredSize(new Dimension(200, 30));

        frame.pack();
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setSize(230,250);
        frame.setResizable(false);
        frame.setVisible(true);      
    }

}

Server

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Scanner;

// Takes in a mathematical operation and the operands from a client and returns the result
// Valid operations are add, sub, multiply, power, divide, remainder, square 
public class mathServer
{ 
    public static void main(String [] args) throws IOException 
    { 
        ServerSocket welcomeSocket = new ServerSocket(50000); //put server online
        while(true)  
        { 
            System.out.println("Waiting for connection...");
            Socket connectionSocket = welcomeSocket.accept();  //open server to connections
            System.out.println("Connection accepted");
            process(connectionSocket);                    //process accepted connection
            System.out.println("Connection closed");
        } 
    }  

    //BufferedReader(Reader r)
    static void process(Socket welcomeSocket) throws IOException 
    {  
        InputStream in = welcomeSocket.getInputStream(); 
        BufferedReader buffer = new BufferedReader(new InputStreamReader(in)); 
        OutputStream out = welcomeSocket.getOutputStream(); 
        PrintWriter print = new PrintWriter(out, true);       

        String input = buffer.readLine(); //get user input from client                

        while(input != null && !input.equals("disconnect")) //check for input, if bye exit connection
        {              
            int answer = operate(input); //perform desired operation on user input
            print.println(answer);          //print out result
            input = buffer.readLine();       //get next line of input                
        }
        welcomeSocket.close(); 
    }  

    //Talk to the client          
    static int operate(String s) 
    { 
        System.out.println(s); //check if same as client input

        Scanner scanner = new Scanner(s); 
        char option = scanner.next().charAt(0);   //gets desired operation

        System.out.println(option); //checks for correct operation 

        switch (option) { 
            case '+': 
                return (scanner.nextInt() + scanner.nextInt());
            case '-':
                return (scanner.nextInt() - scanner.nextInt());
            case '*':
                return (scanner.nextInt() * scanner.nextInt());
            case '^':
                return (int) Math.pow(scanner.nextInt(), scanner.nextInt());
            case '/':
                return scanner.nextInt() / scanner.nextInt();
            case '%':
                return scanner.nextInt() % scanner.nextInt();
            case 's':
                return (int) Math.pow(scanner.nextInt(), 2);
            default:
                return (int) Math.pow(scanner.nextInt(), 3);
        }                       
    }
}
mKorbel
  • 109,525
  • 20
  • 134
  • 319
Alexius Lim
  • 59
  • 1
  • 1
  • 9
  • @peekillet it wont pass the input to the server. And i do not know how to pass it back from the server and back to the client and display it in the UI – Alexius Lim Nov 27 '13 at 14:49

1 Answers1

2

One of the problems is an NullPointerException in actionPerformed(). However it is not visible as you have an empty catch block. You should never have empty catch blocks. Change it to:

catch (Exception e) {
    e.printStackTrace();
}

The members tfInput and tfOutput are null in actionPerformed() as they are never initialized. The constructor mathClient() allocates local variables JTextField tfInput and JTextField tfInput and overshadows the relevant members.

Other than the endless while loop there are several other immediate problems. You should not block Swing's Event Dispatch Thread with a socket. Consider using an auxiliary thread or a SwingWorker.

See Concurrency in Swing for details and examples.

tenorsax
  • 21,123
  • 9
  • 60
  • 107
  • Here is an [example](http://stackoverflow.com/a/3245805/1048330) of a simple client-server using Swing by @trashgod. +1 a long ago :) – tenorsax Nov 27 '13 at 17:29