I’m new to Java Computer Networking and not so great at programming in the first place, however, I was able to construct this Server and Client that is supposed to accept a just one line. A function (add, sub, divide) and two ints and then compute and print the answer. I’m able to connect the two, but when I type the line in it does nothing. Any insight would be appreciated. Thank you!
Server
import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Scanner;
import java.lang.Math;
public class MathServer
{
public static void main(String[] args) throws IOException
{
ServerSocket yourSock = new ServerSocket(50000);
System.out.println("Please Wait....");
while(true)
{
Socket clientSock = yourSock.accept();
System.out.println("Connected!");
process(clientSock);
}
}
static void process(Socket sock) throws IOException
{
InputStream in = sock.getInputStream();
BufferedReader br = new BufferedReader(new InputStreamReader(in));
OutputStream out = sock.getOutputStream();
PrintWriter pw = new PrintWriter(out,true);
//Talk to the client
String input = br.readLine();
while(input != null && !input.equals("disconnect"))
{
Scanner sc = new Scanner(System.in);
String func = sc.nextLine();
double num1 = sc.nextInt();
double num2 = sc.nextInt();
double answer;
switch (func)
{
case "add": answer = num1 + num2;
System.out.println(answer);
break;
case "sub": answer = num1 - num2;
pw.println(answer);
break;
case "multiply": answer = num1 * num2;
pw.println(answer);
break;
case "power": answer = Math.pow(num1, num2);
pw.println(answer);
break;
case "divide": answer = num1 / num2;
pw.println(answer);
break;
case "remainder": answer = num1 % num2;
pw.println(answer);
break;
case "square": answer = Math.sqrt(num1) ;
pw.println(answer);
break;
case "cube": answer= Math.cbrt(num1);
pw.println(answer);
break;
}
sock.close();
}
}
}
Client
import java.io.*;
import java.net.Socket;
import java.util.Scanner;
public class Client
{
public static void main(String[] args) throws Exception
{
Socket Sock = new Socket("localhost", 50000);
BufferedReader br = new BufferedReader(new InputStreamReader(Sock.getInputStream()));
PrintWriter pw = new PrintWriter(Sock.getOutputStream(), true);
Scanner sc = new Scanner(System.in);
String input;
while(true)
{
//System.out.println("Please enter your function and numbers:");
input = sc.nextLine();
pw.println(input);
if(input.equals("disconnect"))
{
System.out.println("You have been disconnected");
break;
}
System.out.println(br.readLine());
}
Sock.close();
}
}
System.ininstead of your input data, you could read from the inputString.readLinestatement within yourwhilestatemet to continue to read from the client.This would look like:
Next, move your
sock.close()statement outside of yourwhileloop.Now, your input commands from the client will appear on a single line, e.g.
Also flush the data from your client: