Socket programming is a topic which has a wide area of knowledge to discuss,But I'm going to demonstrate only about the advantage of using Threads in the socket programming
I'm going to use the Java as my programming language in this demonstration,To ease the work I'm going to run a
Port scanning program with and with out using Threads.But keep in mind if you using a public place like a Computer Laboratory, port scanning may not be allowed.But if you guys use a private place and work through a
localhost then things will be easy.
A Thread and a process have some slight differences,if I go through quickly, a thread is a sub category of a process and which needs a low amount of resources to run and let the computer to create more easily because they are lightweight.
- Java Socket Scanning program which search available(open) ports in the server.
public class MainPrograme {
private static String host;
public static void main(String[] args )
{
host= "localhost";
for (int i = 1; i < 10001; i++)
{
try {
Socket socket = new Socket(host,i);
System.out.println("port "+ i +" is open!");
socket.close();
}
catch (Exception ex) {
System.out.println("port "+ i +" is not open!");
}
}
}
}
|
Port Scanning with out threads for a given time
|
2) Java Socket Scanning program which search available(open) ports in the server which using the Threads class.
//main programme
public class MainPrograme {
private static String host;
public static void main(String[] args) {
host = "localhost";
for (int i = 1; i < 10001; i++) {
PortThread port = new PortThread(host, i);
port.start();
}
}
}
//The ProtThread class which extends Threads class
import java.net.Socket;
public class PortThread extends Thread {
private String host;
private int port;
public PortThread(String host, int port) {
this.host = host;
this.port = port;
}
@Override
public void run() {
try {
Socket socket = new Socket(host, port);
System.out.println("port " + port + " is open!");
socket.close();
return;
} catch (Exception ex) {
System.out.println("port "+port +" is not open!");
}
}
}
|
Scanning Using Threads for a same amount of time |
- Lets get a view of how CPU works when these two program executed!
|
CPU chart for Non Thread Program |
|
CPU chart for a program which use Threads |
Whats the Reason for this?
As you see there's a complete difference of CPU usage in between Thread program execution and non program execution.As you know these days computers usually have multi cores within their CPU's .
So what happen here is when we use threads, each thread assign to each process execution and it uses the CPU's different cores parallely which force the CPU to use a higher amount of resources for a better performance which gives higher number of results in a shorter time period.
So the point is why you use a non threaded program which force you to wait a longer period nervously while a Threaded program can give same results in a short period of time.
Comments
Post a Comment