NumberFormatException in Double.parseDouble() - java

I'm trying to create a client/server application, the server ask the client to write two operands and then to choose an operation when the client choose the operation the server sends him back the result.
when I want to run my program I got this error :
Exception in thread "main" java.lang.NumberFormatException: For input string: "1lient connectée"
at sun.misc.FloatingDecimal.readJavaFormatString(FloatingDecimal.java:1241)
at java.lang.Double.parseDouble(Double.java:540)
at Server.main(Server.java:29)
this is my code :
*Server: *
import java.net.*;
import java.util.*;
import java.io.*;
public class Server {
public static void main (String[] args){
try{
DatagramSocket s = new DatagramSocket(1234);
byte[] sendBuffer = new byte [1024];
byte[] recvBuffer = new byte[1024];
DatagramPacket sendPacket, recvPacket;
String reply = null;
//Get the connection declaration from client
recvPacket = new DatagramPacket(recvBuffer, recvBuffer.length);
s.receive(recvPacket);
System.out.println(new String(recvPacket.getData()));
//Send the first message to client to write the first operand
sendBuffer = "Entré n1 : ".getBytes();
sendPacket = new DatagramPacket(sendBuffer,sendBuffer.length,recvPacket.getAddress(),recvPacket.getPort());
s.send(sendPacket);
//Get the first operand
recvPacket = new DatagramPacket(recvBuffer, recvBuffer.length);
s.receive(recvPacket);
double n1 = Double.parseDouble(new String(recvPacket.getData()));
//Send the second message to client to write the second operand
sendBuffer = "Donner n2 : ".getBytes();
sendPacket = new DatagramPacket(sendBuffer, sendBuffer.length, recvPacket.getAddress(), recvPacket.getPort());
s.send(sendPacket);
//Get the second operand
recvPacket = new DatagramPacket(recvBuffer, recvBuffer.length);
s.receive(recvPacket);
double n2 = Double.parseDouble(new String(recvPacket.getData()));
//Send the third message to client to choose the operation
sendBuffer = "Choisir l'op : \n1-Addition \n2-Soustraction \n3-Multiplication \n4-Division \nVotre choix : ".getBytes();
sendPacket= new DatagramPacket(sendBuffer, sendBuffer.length, recvPacket.getAddress(), recvPacket.getPort());
s.send(sendPacket);
//Get the number of operation
recvPacket = new DatagramPacket(recvBuffer, recvBuffer.length);
s.receive(recvPacket);
reply = new String(recvPacket.getData());
//Traitement
String res = null;
switch(reply){
case "1" :
res = String.valueOf(n1 + n2);
break;
case "2" :
res = String.valueOf(n1 - n2);
break;
case "3" :
res = String.valueOf(n1*n2);
case "4" :
res = (n2 == 0) ? "Division sue zéro" : String.valueOf(n1/n2);
break;
default :
res = "Erreur";
}
//Send the result of the operation to the client
sendBuffer = ("Resultat : "+res).getBytes();
sendPacket = new DatagramPacket(sendBuffer, sendBuffer.length, recvPacket.getAddress(), recvPacket.getPort());
s.send(sendPacket);
}catch(IOException e){
e.printStackTrace();
}
}
}
Client :
import java.net.*;
import java.util.*;
import java.io.*;
public class Client {
public static void main (String[] args) throws UnknownHostException{
DatagramSocket s;
byte[] sendBuffer = new byte[1024];
byte[] recvBuffer = new byte[1024];
DatagramPacket sendPacket, recvPacket;
String reply = null;
final InetAddress ADRSS = InetAddress.getByName("localhost");
final int PORT = 1234;
Scanner cn = new Scanner(System.in);
try{
s = new DatagramSocket();
//Declare connection to server
sendBuffer = "Client connectée".getBytes();
sendPacket = new DatagramPacket(sendBuffer, sendBuffer.length, ADRSS, PORT);
s.send(sendPacket);
//Receive the first message from server
recvPacket = new DatagramPacket(recvBuffer, recvBuffer.length);
s.receive(recvPacket);
System.out.println(new String(recvPacket.getData()));
//Send the answer for the first Message to server (first operand)
sendBuffer = cn.nextLine().getBytes();
sendPacket = new DatagramPacket(sendBuffer, sendBuffer.length, ADRSS, PORT);
s.send(sendPacket);
//Receive the second message from server
recvPacket = new DatagramPacket(recvBuffer,recvBuffer.length);
s.receive(recvPacket);
System.out.println(new String(recvPacket.getData()));
//Send the answer for the second Message to server (second operand)
sendBuffer = cn.nextLine().getBytes();
sendPacket = new DatagramPacket(sendBuffer, sendBuffer.length, ADRSS, PORT);
s.send(sendPacket);
//Receive the third message from server
recvPacket = new DatagramPacket(recvBuffer, recvBuffer.length);
s.receive(recvPacket);
System.out.println(new String(recvPacket.getData()));
//Send the answer for the third Message to server (operation)
sendBuffer = cn.nextLine().getBytes();
sendPacket = new DatagramPacket(sendBuffer, sendBuffer.length, ADRSS, PORT);
s.send(sendPacket);
//Receive the result from server (result of operation)
recvPacket = new DatagramPacket(recvBuffer, recvBuffer.length);
s.receive(recvPacket);
System.out.println(new String(recvPacket.getData()));
}catch(IOException e){
e.printStackTrace();
}
}
}

double n1 = Double.parseDouble(new String(recvPacket.getData()));
This line is causing error, as you are sending String from the client and expecting double on the server. You are likely to face the same issue with the variable n2 as well. So, just treat them as String, and will be well.

Related

Server response blank for some reason?

Have a homework to create client code to send a string split into 2 variables over UDP. Server receives and confirms by sending back the two split variables back to front.
For some reason my response is blank when I run it and not sure why.
can anyone help please?
When I try doing it with integers on another code it works but when I try do strings nothing comes back.
Client code:
import java.io.*;
import java.net.*;
import java.util.Scanner;
public class UDPClient
{
public static void main (String[] args) throws Exception
{
DatagramSocket client = new DatagramSocket();
InetAddress IPAd = InetAddress.getByName("localhost");
byte [] sendData1 = new byte[1024];
byte [] sendData2 = new byte[1024];
byte [] receiveData = new byte [1024];
String input = "";
Scanner in = new Scanner (System.in);
System.out.println("Enter word: ");
input = in.nextLine();
String [] splitWord = input.split("");
int length = splitWord.length;
int evenSplit = 0;
int oddSplit = 0;
String firstHalf = "";
String secondHalf = "";
if (length%2==0)
{
evenSplit = length / 2;
for (int i=0; i<evenSplit; i++)
firstHalf += splitWord[i];
for (int i=evenSplit; i<length;i++)
secondHalf += splitWord[i];
}
else{
oddSplit = (length+1)/2;
for (int i=0; i<oddSplit;i++)
firstHalf += splitWord[i];
for (int i=oddSplit; i<length;i++)
secondHalf += splitWord[i];
}
sendData1 = firstHalf.getBytes();
sendData2 = secondHalf.getBytes();
DatagramPacket sendPacket1 = new DatagramPacket (sendData1,
sendData1.length, IPAd, 2000);
DatagramPacket sendPacket2 = new DatagramPacket (sendData2,
sendData2.length, IPAd, 2000);
client.send(sendPacket1);
client.send(sendPacket2);
DatagramPacket receivePacket = new DatagramPacket (receiveData,
receiveData.length);
String serverReply = new String (receivePacket.getData());
System.out.println ("From server: " + serverReply);
client.close();
}
}
Server code:
import java.io.*;
import java.net.*;
public class UDPServer
{
public static void main (String [] args) throws Exception
{
DatagramSocket server = new DatagramSocket (2000);
byte [] receiveData1 = new byte[1024];
byte [] receiveData2 = new byte[1024];
byte [] sendData = new byte [1024];
while (true)
{
DatagramPacket receivePacket1 = new DatagramPacket
(receiveData1, receiveData1.length);
server.receive(receivePacket1);
DatagramPacket receivePacket2 = new DatagramPacket
(receiveData2, receiveData2.length);
server.receive(receivePacket2);
String firstHalfWord = new String (receivePacket1.getData());
String secondHalfWord = new String (receivePacket2.getData());
InetAddress IPAd = receivePacket1.getAddress();
int port = receivePacket1.getPort();
String response = secondHalfWord + firstHalfWord;
sendData = response.getBytes();
DatagramPacket sendPacket = new DatagramPacket (sendData,
sendData.length, IPAd, port);
server.send(sendPacket);
}
}
}
If I type hello it is mean to reply with lohel (hel + lo back to front)
it simply comes back with "From server:" without any string response.
Before the line String serverReply = new String(receivePacket.getData()); you need to say client.receive(receivePacket);

Sending and receiving byte array in java

I'm having some trouble with my socket programming codes. I have a server tcp that receives the password from client, if it's true, the server will send a file back to client to save, else server will send a byte array with the length is 0.
Then the client will receive the byte array and get the length to compare with 0, if byte length = 0, the client will print out "Wrong password", else it will tell you to enter the file name.
The big problem is the server sent byte array with length = 0 when password is wrong, but client receive byte array with length = 1. I do not know how to solve it....:(
Here is my TCPServer code:
import java.io.*;
import java.net.*;
import java.util.Scanner;
class ServerTCP{
public static void main (String[] args){
try{
ServerSocket ss = new ServerSocket(2018);
System.out.println("\n(*) Server Socket has been created!");
while(true){
Socket s = ss.accept();
InputStream is = s.getInputStream();
OutputStream os = s.getOutputStream();
PrintWriter pw = new PrintWriter(os);
Scanner sc = new Scanner(is);
//Receive information from client
String mail = sc.nextLine();
String pass = sc.nextLine();
System.out.println("Password is: " + pass);
if(matkhau.equals("passtcp")){
String filegui = "D:/filename.pdf";
FileInputStream f = new FileInputStream(filegui);
int lenf = f.available();
byte b2[] = new byte[lenf];
f.read(b2);
f.close();
os.write(b2);
}
else{
byte b[] = new byte[1];
int lenb = 0;
os.write(b);
}
}
}catch(IOException e){
System.out.println("\n(!)An error occured while creating socket!");
}
}
}
Here is my client code
import java.net.*;
import java.io.*;
import java.util.Scanner;
class UdpTcpTest{
public static void main (String[] args){
//String matkhau = new String();
Scanner k = new Scanner(System.in);
try{
//Enter TCP Server's ip
System.out.print("Enter TCP Server's ip: ");
String ip1 = k.nextLine();
//Tao socket
Socket s = new Socket(ip1, 2018);
InputStream is = s.getInputStream();
OutputStream os = s.getOutputStream();
PrintWriter pw = new PrintWriter(os);
String mail = "yourmail#test.com";
String password = "matkhaune";
//send mail and password to server
pw.println(mail); pw.flush();
pw.println(password); pw.flush();
//receive information
byte brecv[] = new byte[60000];
int lenfile = is.read(brecv);
System.out.println("Length = " + lenfile);
if(lenfile <= 1){
System.out.println("Wrong password! Length = " + lenfile);
}
else{
//Save file
System.out.print("Enter file name to save: ");
String filenamed = k.nextLine();
FileOutputStream f = new FileOutputStream(filenamed);
f.write(brecv, 0, lenfile);
f.close();
System.out.println("Saving Scuccess!");
s.close();
}
}catch(IOException e){
System.out.println("Error while excuting!");
}
}
}
I'm having some trouble with my socket programming codes. I have a server tcp that receives the password from client, if it's true, the server will send a file back to client to save, else server will send a byte array with the length is 0.
Impossible.
Then the client will receive the byte array and get the length to compare with 0, if byte length = 0, the client will print out "Wrong password", else it will tell you to enter the file name.
Impossible. You will have to redesign your protocol. You can't send a byte array of zero length over TCP. The minimum is one byte.
The big problem is the server sent byte array with length = 0 when password is wrong
No it didn't. It sent a byte array with length = 1:
byte b[] = new byte[1]; // Here is your byte array of length 1
int lenb = 0; // This is unused. Delete.
os.write(b); // Here you are sending the entire byte array
but client receive byte array with length = 1.
That is correct.
I do not know how to solve it....:(
There is nothing here to solve. Your code is working as designed. You just need to adjust your client to test for a 1-byte receive instead of an impossible zero-byte receive:
int lenfile = is.read(brecv);
System.out.println("Length = " + lenfile);
if(lenfile == 1){

Multicast a file to a group of users

I have a problem to send a file to a group of users. Users could receive the file was sent from server but the file would not be saved if it is less than 8kb.
Here is the code:
MulticastSocketServer
import java.io.*;
import java.net.*;
import java.util.Scanner;
public class MulticastSocketServer{
public static void main(String[] args) {
String fileName;
String address = "235.0.0.1";
int port = 2222;
Scanner in = new Scanner(System.in);
System.out.print("Please enter file name : ");
fileName = in.next();
try (DatagramSocket serverSocket = new DatagramSocket()) {
InetAddress addr = InetAddress.getByName(address);
BufferedReader br = new BufferedReader(new FileReader(fileName + ".txt"));
DatagramPacket fn = new DatagramPacket(fileName.getBytes(),fileName.getBytes().length, addr, port);
serverSocket.send(fn);
DatagramPacket msgPacket = null;
String txt = "";
while((txt = br.readLine())!=null){
msgPacket = new DatagramPacket(txt.getBytes(),txt.getBytes().length, addr, port);
serverSocket.send(msgPacket);
System.out.println(txt);
}
}catch (IOException ex) {ex.printStackTrace();}
}
}
MulticastSocketClient
import java.io.*;
import java.net.*;
public class MulticastSocketClient {
public static void main(String[] args) throws UnknownHostException {
int port = 2222;
String address = "235.0.0.1";
InetAddress addr = InetAddress.getByName(address);
byte[] buf = new byte[64];
byte[] buf2 = null ;
try (MulticastSocket clientSocket = new MulticastSocket(port)){
clientSocket.joinGroup(addr);
DatagramPacket fn = new DatagramPacket(buf, buf.length);
clientSocket.receive(fn);
String name = new String(buf, 0, buf.length);
String fileName = name.trim();
try(PrintWriter pw = new PrintWriter(new FileWriter(fileName+"2.txt"))){
while (true) {
buf2 = new byte [1024];
DatagramPacket msgPacket = new DatagramPacket(buf2, buf2.length);
clientSocket.receive(msgPacket);
String msg = new String(buf2,0,buf2.length);
String txt = msg.trim();
pw.println(txt);
System.out.println(txt);
}
}catch(FileNotFoundException ex){ex.printStackTrace();}
} catch (IOException ex) {ex.printStackTrace();}
}
}
You're never exiting the while (true) loop, because you don't have any mechanism for transmitting end of stream, so you're never closing the PrintWriter, so it isn't flushing its final buffer, so any file < 4096 chars won't get flushed at all, so it will be zero length.
However your code has much worse problems that this. You are assuming:
the filename fits into 1024 characters
every line of the input file fits into 1024 bytes
the filename is received first
all the content packets are received
all the content packets are received in order
all the content packets are received exactly once
the length of every datagram is 1024
the data is text, not binary, and can be converted losslessly to a String
You're using UDP. That means that most of these assumptions are invalid.

Data wont send through DatagramSocket

For some reason, the data in my datagramsocket wont send. Im trying to make a simple chatclient.
Here is how my chat client is going to work:
The person enters the username
They enter the IP
It connects
They send messages
Here is my code:
Client 1 (Sends and recieves):
// Server Info
public static int serverPort = 8743;
public static String serverName = "ServerName";
// Functions for the server
#SuppressWarnings("resource")
public static void main(String args[]) throws Exception {
DatagramSocket serverSocket = new DatagramSocket();
byte[] receiveData = new byte[1024];
System.out.println("You are now the host.");
boolean enteredDetails = false;
String username = null;
String ipAddress = null;
System.out.print("Enter your username: ");
Scanner userInput = new Scanner(System.in);
if (userInput.hasNext()) {
username = userInput.next();
}
System.out.print("Enter the IP: ");
if (userInput.hasNext()) {
ipAddress = userInput.next();
enteredDetails = true;
}
while (true) {
Scanner message = new Scanner(System.in);
if (message.hasNextLine()) {
String messageFormat = username + ": " + message.nextLine();
byte[] sendData = messageFormat.getBytes();
InetAddress IPAddress = InetAddress.getByName(ipAddress);
DatagramPacket sendPacket = new DatagramPacket(sendData,
sendData.length, InetAddress.getByName(ipAddress), 9876);
serverSocket.send(sendPacket);
System.out.println(messageFormat);
}
// Recieve text
DatagramPacket receivePacket = new DatagramPacket(receiveData,
receiveData.length);
serverSocket.receive(receivePacket);
String sentence = new String(receivePacket.getData());
System.out.println(sentence);
}
}
For the second client (recieves only):
#SuppressWarnings("resource")
public static void main(String args[]) throws Exception {
DatagramSocket serverSocket = new DatagramSocket();
byte[] receiveData = new byte[1024];
boolean enteredDetails = false;
String username = null;
String ipAddress = null;
System.out.print("Enter your username: ");
Scanner userInput = new Scanner(System.in);
if (userInput.hasNext()) {
username = userInput.next();
}
System.out.print("Enter the IP: ");
if (userInput.hasNext()) {
ipAddress = userInput.next();
enteredDetails = true;
}
while (true) {
// Recieve text
DatagramPacket receivePacket = new DatagramPacket(receiveData,
receiveData.length);
serverSocket.receive(receivePacket);
String sentence = new String(receivePacket.getData());
System.out.println(sentence);
}
}
Client 1:
DatagramPacket sendPacket = new DatagramPacket(sendData,
sendData.length, InetAddress.getByName(ipAddress), 9876);
This client is sending to port 9876.
Client 2:
DatagramSocket serverSocket = new DatagramSocket();
There's no way this client is ever going to receive anything, as it is receiving on an unknown port which is different every time you run it. It should be:
DatagramSocket serverSocket = new DatagramSocket(9876);

Finding GCD, Socket Programming in Java

I have written the following two codes for finding GCD of two numbers. (via UDP Server)
GCD_UDPClient.java
import java.io.*;
import java.net.*;
class GCD_UDPClient
{
public static void main(String args[]) throws Exception
{
BufferedReader InFromUser = new BufferedReader(new InputStreamReader(System.in));
DatagramSocket ClientSocket = new DatagramSocket();
InetAddress IPAddress = InetAddress.getByName("localhost");
byte[] SendData = new byte[1024];
byte[] ReceiveData = new byte[1024];
System.out.print("First Number: ");
String input1 = InFromUser.readLine();
System.out.print("Second Number: ");
String input2 = InFromUser.readLine();
String Input = input1 + ' ' +input2;
SendData = Input.getBytes();
DatagramPacket SendPacket = new DatagramPacket(SendData, SendData.length, IPAddress, 9836);
ClientSocket.send(SendPacket);
DatagramPacket ReceivePacket = new DatagramPacket(ReceiveData, ReceiveData.length);
ClientSocket.receive(ReceivePacket);
String ModifiedInput = new String(ReceivePacket.getData());
System.out.println("GCD From Server: " +ModifiedInput);
ClientSocket.close();
}
}
GCD_UDPServer.java
import java.io.*;
import java.net.*;
#SuppressWarnings("unused")
class GCD_UDPServer
{
#SuppressWarnings("resource")
public static void main(String args[]) throws Exception
{
DatagramSocket ServerSocket = new DatagramSocket(9836);
byte[] ReceiveData = new byte[1024];
byte[] SendData = new byte[1024];
while(true)
{
DatagramPacket ReceivePacket = new DatagramPacket(ReceiveData, ReceiveData.length);
ServerSocket.receive(ReceivePacket);
String input = new String(ReceivePacket.getData());
InetAddress IPAddress = ReceivePacket.getAddress();
int port = ReceivePacket.getPort();
int ar[] = new int[2],i=0;
for (String Number: input.split(" ", 2))
{
ar[i] = Integer.parseInt(Number);
i=i+1;
}
String Answer = Integer.toString(calculategcd(ar[0],ar[1]));
SendData = Answer.getBytes();
DatagramPacket SendPacket = new DatagramPacket(SendData, SendData.length, IPAddress, port);
ServerSocket.send(SendPacket);
}
}
public static int calculategcd(int a, int b)
{
if(b%a == 0)
return a;
else
return calculategcd(b%a,a);
}
}
ClientSocket.receive(ReceivePacket); doesn't seem to work properly, any clues why? Full codes are posted only for clarity.
Output given by the above codes:
First Number: 5
Second Number: 25
[waits indefinitely]
Output Required:
First Number: 5
Second Number: 25
GCD From Server: 5
You are sending 1024 bytes to the server, and you placed your data in a String like "5 25". When you receive the data you split it and you will have "5", and "25" followed by the other bytes in your buffer. Either you use Number.trim() to throw away those extra bytes, or you send a smaller packet (if that is possible).
I had a test , the GCD_UDPServer.java have a exception like
Exception in thread "main" java.lang.NumberFormatException: For input string: "12"
at java.lang.NumberFormatException.forInputString(NumberFormatException.java:65)
at java.lang.Integer.parseInt(Integer.java:492)
at java.lang.Integer.parseInt(Integer.java:527)
at GCD_UDPServer.main(GCD_UDPServer.java:24)
and simply change line 24
ar[i] = Integer.parseInt(Number);
to
ar[i] = Integer.parseInt(Number.trim());
and it works properly.

Categories

Resources