โปรแกรมหาเลขเฉพาะ (prime number) ทำงานระหว่าง client/server

ลองเขียนโปรแกรมทบทวนความรู้ดูซะหน่อยเตรียมความพร้อม ก็เลือกโปรแกรมหา prime number โดยจะแยกเป็นทางฝั่ง
Server – จะทำการประมวลผลหาค่า
Client – ก็เรียกใช้การทำงานทางฝั่ง Server ให้ทำงานให้ แล้วส่งผลลัพท์มาให้ client

โปรแกรมที่เขียนก็เขียนกับ java โดยอาศัยการส่งข้อมูลทาง Socket ทาง port 6666

(ยังทำงานบน Textmode ไว้หลังจากนี้จะทำแบบ GUI ครับ)
[java]import java.net.*;
import java.io.*;
class worker extends Thread
{
Socket sock;
BufferedReader in;
PrintStream out;
int min;
int max;
StringBuffer buf;
public worker(Socket s)
{
sock = s;
min = 0;
max = 0;
buf = new StringBuffer("");
}
public void run()
{
try
{
in = new BufferedReader(new InputStreamReader(sock.getInputStream()));
out = new PrintStream(sock.getOutputStream());
String line;
while ((line = in.readLine()) != null)
{
min =0;
max =0;
if ((line.length() >= 4) && (line.substring(0,3).equals("max")))
{
max = Integer.parseInt(line.substring(3).trim());
countPrime(min,max);
out.println("prime number from " +min +" to "+max+" is : " + buf.toString());
out.flush();
}
else break;
}
System.out.println("Find prime number finished from "+min+" to "+max);
sock.close();
}
catch (IOException ioe)
{System.out.println(ioe);}
}
public void countPrime(int min, int max)
{
for (int i = 0; i <= max ; i++)
if (isPrime(i)){
buf.append(i+ " ");
}
}
public boolean isPrime(int i)
{
for (int j = 2; j*j <= i ; j++)
if (i%j == 0)
return false;
return true;
}
}
public class primeServ
{
public static void main(String args[]) throws IOException
{
Socket sock;
ServerSocket servsock = new ServerSocket(6666);
while(true)
{
sock = servsock.accept();
new worker(sock).start();
}
}
}[/java]

ฝั่ง Client
[java]import java.io.*;
import java.net.*;
public class primeClient
{
public static void main(String args[]) throws IOException
{
if ((args.length != 2) )
{
System.out.println("Usage : java primeClient ");
System.exit(1);
}
Socket sock = new Socket(args[0],6666);
BufferedReader in = new BufferedReader(new InputStreamReader(
sock.getInputStream()));
PrintStream out = new PrintStream(sock.getOutputStream());
out.println("max"+args[1]);
out.flush();
String line = in.readLine();
System.out.println(line);
sock.close();
}
}[/java]

engineerball Written by: