How To Get Sent Message (As Server) Using Java Socket Programming

I am new on socket programming. This is what I have on my first learning about socket programming.

The scenario is an app will send message using socket to my app which is act as server. There will be a main class that create socket server and then create thread to handle the incoming message. Each incoming message will be processed by a worker class. The worker class will print the message on this example.

Here is the code:

package simpleserver;

import java.io.IOException;
import java.net.ServerSocket;

/**
 *
 * @author ariestania.winda
 */
public class SimpleServer {

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) throws IOException{
        ServerSocket server = new ServerSocket(8080);       
        new RequestThread(server).start();        
    }
}

package simpleserver;

import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;


/**
 *
 * @author ariestania.winda
 */
public class RequestThread extends Thread {

    private ServerSocket server;
    private ArrayBlockingQueue<Runnable> arrayBlockingQueue = new ArrayBlockingQueue<Runnable>(1);
    ThreadPoolExecutor pool;
    
    public RequestThread(ServerSocket server) {            
        this.server = server;
        if(this.pool==null){
            this.pool = new ThreadPoolExecutor(5, 6, 5, TimeUnit.MINUTES, arrayBlockingQueue);
        }
    }   
    
    @Override
    public void run() {
        while (true) {            
            try {
                Socket socket = server.accept();
                if(pool.getActiveCount() < pool.getMaximumPoolSize()){
                    new WorkerThread(socket).start();
                } else {
                    this.sleep(1000);
                }                
            } catch(InterruptedException ie){
                System.out.println("enterup" + ie.getMessage());
            }
            catch (IOException ex) {
                System.out.println("error: " + ex.getMessage());
            }    
        }            
    }
    
}
package simpleserver;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.Socket;

/**
 *
 * @author ariestania.winda
 */
public class WorkerThread extends Thread{

    private Socket socket;
    
    public WorkerThread(Socket socket) {
        this.socket = socket;
    }
    
    
    @Override
    public void run() {
        try {            
            BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
            String str;            
            while ((str = in.readLine())!= null && str.trim().length()>0) {
                    System.out.println(str);
            }
        } catch (Exception e) {
            System.out.println("error : " + e.getMessage());
        }
    }
    
}

Hope this article can help even just a bit 🙂

 

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s