TCP based calculator (Java)

Keywords: Programming Java socket calculator

A calculator based on TCP communication, the client sends data to the server through the button, the server calculates and processes the data, and sends the calculation result back to the client. It uses multithreading to enable.

Server thread:
package com.netproject2;

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;

public class CalculatorServer extends Thread{
public final double PI=3.1415927; / / define pi
Socket client; / / define client socket
DataInputStream datain=null; / / define data input stream to receive data
InputStream in=null;
DataOutputStream dataout=null; / / define data output stream to transfer data
OutputStream out=null;
float num_one;
float num_two;
float result; / / define the calculation result
int symbol; / / define symbol
public CalculatorServer(Socket client){
this.client=client;
}

public  void run() {
	
	try {
		in=client.getInputStream();//Input stream reception
		datain=new DataInputStream(in);//Stream to data
		out=client.getOutputStream();
		dataout=new DataOutputStream(out);
	while(true){
		symbol=datain.readInt();//Read symbols replaced by numbers
		switch(symbol){//Calculation
			case 1:
				num_two=datain.readFloat();//Read the number of the second input
			    result=(float) Math.sin(num_two*PI/180);
			    dataout.writeFloat(result);break;//Transfer calculation results to client
			case 2:
				num_two=datain.readFloat();//Read the number of the second input
		   	    result=(float) Math.cos(num_two*PI/180);
		        dataout.writeFloat(result);break;//Transfer calculation results to client
			case 3:
				num_two=datain.readFloat();//Read the number of the second input
		        result=(float) Math.tan(num_two*PI/180);
		        dataout.writeFloat(result);break;//Transfer calculation results to client
			case 4:
				num_two=datain.readFloat();//Read the number of the second input
		        result=(float) Math.sqrt(num_two*PI/180);
		        dataout.writeFloat(result);break;//Transfer calculation results to client
			case 5:
				num_one=datain.readFloat();//Read integer data
			    num_two=datain.readFloat();//Read the number of the second input
			    result=num_one+num_two;
			    dataout.writeFloat(result);break;//Transfer calculation results to client
			case 6:
				num_one=datain.readFloat();//Read integer data
				num_two=datain.readFloat();//Read the number of the second input
				result=num_one-num_two;
				dataout.writeFloat(result);break;//Transfer calculation results to client
			case 7:
				num_one=datain.readFloat();//Read integer data
				num_two=datain.readFloat();//Read the number of the second input
				result=num_one*num_two;
				dataout.writeFloat(result);break;//Transfer calculation results to client
			case 8:
				num_one=datain.readFloat();//Read integer data
				num_two=datain.readFloat();//Read the number of the second input
				result=num_one/num_two;
				dataout.writeFloat(result);break;//Transfer calculation results to client
			default:break;
		}
			} 
	}catch (IOException e) {
				e.printStackTrace();
			} 
	try {//Close sockets and streams
		in.close();
		datain.close();
		out.close();
		dataout.close();
		client.close();
	} catch (IOException e) {
		System.out.println(client.isConnected());
		e.printStackTrace();
			}
	}
}

Server master method:
package com.netproject2;

import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;

public class DemoServer {
//The client can be reconnected after disconnection
public static void main(String[] args) {
ServerSocket server=null;
Socket client=null;
try {
server=new ServerSocket(8866); / / create server socket
System.out.println("server started, waiting for client connection..." );
}catch (IOException e) {
System.out.println("server socket creation error");
}
while(true){
try {
client=server.accept(); / / connect to the client
System.out.println("client connected, can communicate..." +client);
} catch (IOException e1){
System.out.println("client connection error");
}
if(client!=null) {/ / used to connect multiple clients at the same time
new CalculatorServer(client).start();
}
}
}
}
Client thread:
package com.netproject2;

import java.awt.BorderLayout;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.SwingConstants;

public class CalculatorClient extends JFrame implements Runnable,ActionListener{

	Socket client=null;
	DataInputStream datain=null;
	InputStream in=null;
	DataOutputStream dataout=null;
	OutputStream out=null;
	String[][] inputButtonNames={{"sin","cos","tan","√"},{"1","2","3","+"},{"4","5","6","-"},{"7","8","9","*"},{".","0","=","/"}};
	//Define 2D array mount button name inputButtonNames
	JTextField show=new JTextField();//Create input box textField
	JButton[] inButton=new JButton[20];//Create input buttonbutton
	String[] resetButtonNames={"    clear        empty     ","    clear       except      "};//Define clear button name resetButtonNames
	JButton[] resetButton=new JButton[2];//Create a clear buttonresetbutton
	String tempText="";//Button number (string) used to temporarily store the first acquisition
	
	int symbol=0;//Used to judge operation symbols
	float num_one;//Used to store the number before the input operation symbol (converted)
	float num_two;//Used to store the number after the input operation symbol (converted)
	float result;//Used to store operation results
	int number=0;//Number of times to judge the input 	 
	boolean com=false;//Used to determine whether the operation symbol and decimal point are entered
	
	
	public CalculatorClient(){//Parameterless constructor of the evaluation panel		
		super("Client");//Call parent method
		this.setBounds(300,300,252, 264);//Set the size of the form and where it appears on the screen
		
		JPanel ibp=new JPanel();//Create input box panel input box panel
		show.setText("0");//Set input box initial number "0"
		show.setColumns(21);//Set the number of input box columns
		show.setEditable(false);//Set input box to non editable state
		show.setHorizontalAlignment(SwingConstants.RIGHT);//Set the orientation of the input box: North
		ibp.add(show);//Add an input box to the input box panel
		this.add(ibp, BorderLayout.NORTH);//Set orientation of input box panel: set North
		
		JPanel bp=new JPanel();//Set input button panel
		GridLayout gridLayout=new GridLayout(5,4,4,4);//Grid layout
		bp.setLayout(gridLayout);//Input button panel using grid layout
		for(int i=0;i<5;i++){//Insert input buttons one by one with array and loop
			for(int j=0;j<inputButtonNames[0].length;j++){
				inButton[i*4+j]=new JButton(inputButtonNames[i][j]);
				bp.add(inButton[i*4+j]);//Add input button to input button panel
				inButton[i*4+j].addActionListener(this);//Give action monitor
			}
		}
		this.add(bp, BorderLayout.SOUTH);//Set input button panel orientation: set South
		
		JPanel cbp=new JPanel();//Create clear button and triangle function button panel		
		for(int i=0;i<resetButtonNames.length;i++){////Use array and loop to implant clear buttons one by one
			resetButton[i]=new JButton(resetButtonNames[i]);
			cbp.add(resetButton[i]);//Add clear button to clear button
			resetButton[i].addActionListener(this);//Give action monitor
		}
		this.add(cbp, BorderLayout.CENTER);//Set clear button panel orientation: Center
		
		this.setVisible(true);//Set form visible
		
		try {
			client=new Socket("localhost",8866);//Create local socket
		} catch (IOException e4) {
			e4.printStackTrace();
		}
		try {
			out=client.getOutputStream();
			dataout=new DataOutputStream(out);
			in=client.getInputStream();
			datain=new DataInputStream(in);
		} catch (IOException ee) {
			ee.printStackTrace();
		}			
	}
	
	public void run(){//Thread running
		
	}
	@Override
	public void actionPerformed(ActionEvent e) {
		
		if(e.getSource() == inButton[0]) {//Action monitoring of sin
			com=true;
			number=0;
			symbol=1;
			show.setText("sin");
			}
		else if(e.getSource() == inButton[1]) {//cos action monitoring
			com=true;
			number=0;
			symbol=2;
			show.setText("cos");
			}
		else if(e.getSource() == inButton[2]) {//tan's action monitoring
			com=true;
			number=0;
			symbol=3;
			show.setText("tan");
			}
		else if(e.getSource() == inButton[3]) {//Action monitoring of Kaifang
			com=true;
			number=0;
			symbol=4;
			show.setText("√");
			}
		else if (e.getSource() == inButton[4]) {//Action monitoring of digit 1
			if(com==true||number==0){//First input
			show.setText("1");//Output the first input number
			number=1;
			com=false;
			}
			else{				//Non first input
				tempText=show.getText();//Get the first entered number
				show.setText(tempText+"1");//Output the number of n inputs together
			}	
		}
		else if (e.getSource() == inButton[5]) {//Digital 2 action monitoring
			if(com||number==0){
				show.setText("2");
				number=1;
				com=false;
				}
				else{
					tempText=show.getText();
					show.setText(tempText+"2");
				}	
			}
		else if (e.getSource() == inButton[6]) {//Action monitoring of digit 3
			if(com||number==0){
				show.setText("3");
				number=1;
				com=false;
				}
				else{
					tempText=show.getText();
					show.setText(tempText+"3");
				}	
			}
		else if (e.getSource() == inButton[7]) {	//Plus action monitoring		
			com=true;
			number=0;
			symbol=5;
			num_one=Float.parseFloat(show.getText());//Convert the acquired string to a number
			show.setText("+");
		}
		else if (e.getSource() == inButton[8]) {//Action monitoring of digit 4
			if(com||number==0){
				show.setText("4");
				number=1;
				com=false;
				}
				else{
					tempText=show.getText();
					show.setText(tempText+"4");
				}	
			}
		else if (e.getSource() == inButton[9]) {//Action monitoring of digit 5
			if(com||number==0){
				show.setText("5");
				number=1;
				com=false;
				}
				else{
					tempText=show.getText();
					show.setText(tempText+"5");
				}	
			}
		else if (e.getSource() == inButton[10]) {//Action monitoring of digit 6
			if(com||number==0){
				show.setText("6");
				number=1;
				com=false;
				}
				else{
					tempText=show.getText();
					show.setText(tempText+"6");
				}	
			}
		else if (e.getSource() == inButton[11]) {//Action monitoring of minus sign
			com=true;
			number=0;
			symbol=6;
			num_one=Float.parseFloat(show.getText());//Convert the acquired string to a number
			show.setText("-");
			}
		else if (e.getSource() == inButton[12]) {//Action monitoring of digit 7
			if(com||number==0){
				show.setText("7");
				number=1;
				com=false;
				}
				else{
					tempText=show.getText();
					show.setText(tempText+"7");
				}	
			}
		else if (e.getSource() == inButton[13]) {//Action monitoring of digit 8
			if(com||number==0){
				show.setText("8");
				number=1;
				com=false;
				}
				else{
					tempText=show.getText();
					show.setText(tempText+"8");
				}	
			}
		else if (e.getSource() == inButton[14]) {//Action monitoring of digit 9
			if(com||number==0){
				show.setText("9");
				number=1;
				com=false;
				}
				else{
					tempText=show.getText();
					show.setText(tempText+"9");
				}	
			}
		else if (e.getSource() == inButton[15]) {//Multiple sign action monitoring
			com=true;
			number=0;
			symbol=7;
			num_one=Float.parseFloat(show.getText());//Convert the acquired string to a number
			show.setText("*");
			}
		else if (e.getSource() == inButton[16]) {
			if(com||number==0){//To be improved: make it impossible to press this button for the first time
				show.setText(".");
				number=1;
				com=false;
				}
				else{//Determine whether the obtained string contains decimal point "."
					tempText=show.getText();
					if(tempText.indexOf(".")==-1){
						show.setText(tempText+".");
					}
					else{show.setText(tempText);}
				}	
			}
		else if (e.getSource() == inButton[17]) {//Action monitoring of digit 0
			if(com||number==0){
				show.setText("0");
				number=1;
				com=false;
				}
				else{
					tempText=show.getText();
					show.setText(tempText+"0");
				}	
			}
		else if (e.getSource() == inButton[18]) {//Equal sign action monitoring
			num_two=Float.parseFloat(show.getText());//Get the string after the input operation symbol and convert it
			
			switch(symbol){
				case 1:try {
					   dataout.writeInt(symbol);
					   dataout.writeFloat(num_two);
					   result=datain.readFloat();
				       number=0;//Ibid.
					   show.setText(""+result);
					} catch (IOException e2) {
					e2.printStackTrace();
					}break;
				case 2:try {
					   dataout.writeInt(symbol);
					   dataout.writeFloat(num_two);
					   result=datain.readFloat();
				       number=0;//Ibid.
					   show.setText(""+result);
					} catch (IOException e2) {
					e2.printStackTrace();
					}break;
				case 3:try {
					   dataout.writeInt(symbol);
					   dataout.writeFloat(num_two);
					   result=datain.readFloat();
				       number=0;//Ibid.
					   show.setText(""+result);
					} catch (IOException e2) {
					e2.printStackTrace();
					}break;
				case 4:try {
					   dataout.writeInt(symbol);
					   dataout.writeFloat(num_two);
					   result=datain.readFloat();
				       number=0;//Ibid.
					   show.setText(""+result);
					} catch (IOException e2) {
					e2.printStackTrace();
					}break;
				case 5:try {
					   dataout.writeInt(symbol);
					   dataout.writeFloat(num_one);
					   dataout.writeFloat(num_two);
					   result=datain.readFloat();
				       number=0;//Ibid.
					   show.setText(""+result);
					} catch (IOException e1) {
					e1.printStackTrace();
					}break;
				case 6:try {
					   dataout.writeInt(symbol);
					   dataout.writeFloat(num_one);
					   dataout.writeFloat(num_two);
					   result=datain.readFloat();
					   number=0;//Ibid.
					   show.setText(result+"");
					} catch (IOException e1) {
					e1.printStackTrace();
					}break;
				case 7:try {
					   dataout.writeInt(symbol);
					   dataout.writeFloat(num_one);
					   dataout.writeFloat(num_two);
					   result=datain.readFloat();
					   number=0;//Ibid.
					   show.setText(result+"");
					} catch (IOException e1) {
					e1.printStackTrace();
					}break;
				case 8:try {
					   dataout.writeInt(symbol);
					   dataout.writeFloat(num_one);
					   dataout.writeFloat(num_two);
					   result=datain.readFloat();
					   number=0;//Ibid.
					   show.setText(result+"");
					} catch (IOException e1) {
					e1.printStackTrace();
					}break;
				default:number=0;break;//Ibid.
			}
		}
		else if(e.getSource() == inButton[19]) {//Action monitoring of division sign
			com=true;
			number=0;
			symbol=8;
			num_one=Float.parseFloat(show.getText());//Convert the acquired string to a number
			show.setText("/");
			}
		else if (e.getSource() == resetButton[0]){//Clear button AC
			number=0;//The effect is the same as the interpretation of the equal sign "number=0"
			symbol=0;//Reset symbol
			show.setText("0");
		}
		else if (e.getSource() == resetButton[1]){//Single byte clear button C
			number=0;//The effect is the same as the interpretation of the equal sign "number=0"
			symbol=0;//Reset symbol
		 	tempText=show.getText();
			if(tempText.equals("sin")||tempText.equals("cos")||tempText.equals("tan")||(tempText.length()-1)==0){//Determine whether tempText is a single byte
				show.setText("0");
			}
			else {
				show.setText(tempText.substring(0,tempText.length()-1));
				 if(tempText.length()==0)
					 {show.setText("0");}
				 }
		}		
	}	
}

Client main method:
package com.netproject2;

public class DemoClient {

public static void main(String[] args) {
	
	CalculatorClient p = new CalculatorClient();
     new Thread(p).start();
}

}

Posted by JAM on Fri, 13 Dec 2019 12:19:39 -0800