Sunday, 17 July 2016

Client Program for Prime Number | Java Networking



The client is one who requests or sends commands to the server for a certain operation. In this example, we are requesting the server to check if the number provided is prime or not.

For complete explanation check this post: Java Networking: Server Client Explained [Student Friendly Explanation]


import java.net.*;
import java.util.*;
import java.io.*;

class Client
{
public static void main(String args[]) throws IOException
{

int num,num1;
System.out.println("Enter a number");
Scanner scan = new Scanner (System.in);
num = scan.nextInt();

try{
System.out.println("Sending number for testing");
Socket s = new Socket("localhost",1357);

DataOutputStream dout = new DataOutputStream(s.getOutputStream());
dout.write(num);

DataInputStream din = new DataInputStream(s.getInputStream());
num1 = din.read();

if(num1==0){
System.out.println("Number is prime");
}
if(num1==1){
System.out.println("Number is not prime");
}

s.close();
}catch(UnknownHostException e)
{
System.out.println(e.getMessage());
}
}
}

0 comments:

Post a Comment