Finding GCD, Socket Programming in Java - 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.

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);

How to run Client program on fixed port in UDP connectionless client - server pair in java

I am trying to understand UDP connectionless client - server pair. I got some code in the Book Computer Networking: A Top Down Approach.
The Programs are as follows:-
UDPServer.java:
import java.io.*;
import java.net.*;
class UDPServer
{
public static void main(String args[]) throws Exception
{
DatagramSocket serverSocket = new DatagramSocket(9876);
byte[] receiveData = new byte[1024];
byte[] sendData = new byte[1024];
while(true)
{
DatagramPacket receivePacket = new DatagramPacket(receiveData, receiveData.length);
serverSocket.receive(receivePacket);
String sentence = new String( receivePacket.getData());
System.out.println("RECEIVED: " + sentence);
InetAddress IPAddress = receivePacket.getAddress();
int port = receivePacket.getPort();
String capitalizedSentence = sentence.toUpperCase();
sendData = capitalizedSentence.getBytes();
DatagramPacket sendPacket =
new DatagramPacket(sendData, sendData.length, IPAddress, port);
serverSocket.send(sendPacket);
}
}
}
UDPClient.java
import java.io.*;
import java.net.*;
class 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];
String sentence = inFromUser.readLine();
sendData = sentence.getBytes();
DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length, IPAddress, 9876);
clientSocket.send(sendPacket);
DatagramPacket receivePacket = new DatagramPacket(receiveData, receiveData.length);
clientSocket.receive(receivePacket);
String modifiedSentence = new String(receivePacket.getData());
System.out.println("FROM SERVER:" + modifiedSentence);
clientSocket.close();
}
}
In the given code we have fixed the port no for the Server ,i.e., 9876.
I am curious to know that how to fix the port for Client, as we did for Server in the given java program, so that message can be returned to Client on the Specific Port.
For example, if the
client will send a UDP message to the server, the server will start and run on port number 9876 and return the original message to the client on port 9877. Please help.
You don't need a fixed port at the client, any more than the client needs a fixed IP address. Your own code should already work correctly. However there are other issues:
String sentence = new String( receivePacket.getData());
Wrong. It should be String sentence = new String( receivePacket.getData(), receivePacket.getOffset(), receivePacket.getLength());.
System.out.println("RECEIVED: " + sentence);
InetAddress IPAddress = receivePacket.getAddress();
int port = receivePacket.getPort();
String capitalizedSentence = sentence.toUpperCase();
sendData = capitalizedSentence.getBytes();
DatagramPacket sendPacket =
new DatagramPacket(sendData, sendData.length, IPAddress, port);
serverSocket.send(sendPacket);
This code will send the reply back to from whence the request came. An easier way is to use the same DatagramPacket for both receive and send, and just change the data.

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);

NumberFormatException in Double.parseDouble()

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.

Categories

Resources