Assignment is next: You need to create an application for adding two numbers. The addition operation itself needs to take place on the server, which accepts the two additions and delivers the result. Therefore, it is necessary that the solution contains two components: server and client.
Within the client application, the user needs to be able to enter two numbers using the Scanner class. Values need to be placed inside variables and then sent to the server part of the application. Values can be sent together or separately. After accepting the value, the server should add the passed numbers and deliver the total to the client. The obtained total must be displayed on the client at the output.
I can't manage to code so that the addition is done on the server and the result is sent to the client.
Code thah I use is next:
Client:
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.Socket;
import java.util.Scanner;
public class Client {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter first number: ");
int a = sc.nextInt();
System.out.println("Enter second number: ");
int b = sc.nextInt();
int sum = a+b;
try(Socket socket = new Socket("localhost", 1080);
BufferedReader bis = new BufferedReader(new InputStreamReader(socket.getInputStream()));
BufferedOutputStream bos = new BufferedOutputStream(socket.getOutputStream())){
bos.write(sum);
bos.flush();
String line = bis.readLine();
System.out.println(line);
}catch(IOException exc){
System.out.println(exc.getMessage());
}
}
}
Server:
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.ServerSocket;
import java.net.Socket;
public class Server {
public static void main(String[] args) {
System.out.println("Listening");
try(ServerSocket serverSocket = new ServerSocket(1080);
Socket socket = serverSocket.accept();
BufferedReader bis = new BufferedReader(new InputStreamReader(socket.getInputStream()));
BufferedOutputStream bos = new BufferedOutputStream(socket.getOutputStream())){
String line = bis.readLine();
bos.write(("Rezultat je:" + line).getBytes());
bos.flush();
}catch (IOException exc){
System.out.println(exc.getMessage());
}
}
}