The server is one who processes the requests or commands sent by the client for a certain operation. In this example, the server is going to check if the number provided is prime or not. It will return value as 0 or 1 to the client.
For complete explanation check this post: Java Networking: Server Client Explained [Student Friendly Explanation]
import java.net.*;
import java.io.*;
import java.util.*;
class Server1
{
public static void main(String args[]) throws IOException
{
int x,y=1,flag=0;
try{
System.out.println("Running and ready to receive number");
ServerSocket ss = new ServerSocket(1357);
Socket s = ss.accept();
DataInputStream din = new DataInputStream(s.getInputStream());
x = din.read();
System.out.println("You have entered " + x);
for(int i=2; i<x ; i++)
{
if(x%i==0){
flag++;
}}
if(flag==1){y=0;}
DataOutputStream dout = new DataOutputStream(s.getOutputStream());
dout.write(y);
dout.close();
ss.close();
}catch(UnknownHostException e)
{
System.out.println(e.getMessage());
}
}
}

0 comments:
Post a Comment