I've been trying to write a client process that will communicate with a serve.
I used the same code below but instead of scanner i used BufferedReader and the client input was a string. Furthermore, the server just changes the string to uppercase and sends it back to the client to be displayed on the screen. It worked.
However, when i changed the code so that the client can enter a double number [(ex: 1.6) the server should round it and send it back so that it'll be printed on the screen], i get no response.
And i got this error:
run:
Exception in thread "main" java.util.InputMismatchException
at java.util.Scanner.throwFor(Scanner.java:864)
at java.util.Scanner.next(Scanner.java:1485)
at java.util.Scanner.nextDouble(Scanner.java:2413)
at socketserver.SocketServer.main(SocketServer.java:38)
Java Result: 1
notes:
- I am using NetBeans.
- I used Scanner instead of using BufferedReader so that i'll be able to read a double number.
Client class
package socketclient;
import java.io.*;
import java.net.*;
import java.util.Scanner;
public class SocketClient {
/**
* @param args the command line arguments
*/
public static void main(String args[]) throws Exception
{
double inputDouble;
double modifiedNum;
Scanner inFromUser = new Scanner(System.in);
Socket clientSocket = new Socket("localhost", 6789);
DataOutputStream outToServer =
new DataOutputStream(clientSocket.getOutputStream());
Scanner inFromServer = new Scanner(clientSocket.getInputStream());
inputDouble = inFromUser.nextDouble();
outToServer.writeDouble(inputDouble);
modifiedNum = inFromServer.nextDouble();
System.out.println("FROM SERVER: " + modifiedNum);
outToServer.close();
clientSocket.close();
}
}
Server class
package socketserver;
import java.io.*;
import java.net.*;
import java.util.Scanner;
public class SocketServer {
/**
* @param args the command line arguments
*/
public static void main(String args[]) throws Exception
{
double clientNum;
double roundedNum;
ServerSocket welcomeSocket = new ServerSocket(6789);
while(true) {
Socket connectionSocket = welcomeSocket.accept();
Scanner inFromClient = new Scanner(connectionSocket.getInputStream());
DataOutputStream outToClient =
new DataOutputStream(connectionSocket.getOutputStream());
clientNum = inFromClient.nextDouble();
roundedNum= Math.round(clientNum);
outToClient.writeDouble(roundedNum);
}
}
}