Demo entry 6311132

TCPHandler.java

   

Submitted by anonymous on Oct 24, 2016 at 16:13
Language: Java. Code size: 2.6 kB.

/**
* @Author: mdrhri-6
* @Date:   2016-10-24T04:08:04+02:00
* @Last modified by:   mdrhri-6
* @Last modified time: 2016-10-24T04:14:31+02:00
*/



import java.io.DataOutputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Hashtable;
import java.util.Random;

public class TCPHandler extends Thread{

    Socket connectionSocket = null;
    String ipAddress;
    Integer portNumber;
    Hashtable<String, Object>  storage=null;

    public TCPHandler(Socket connectionSocket, Hashtable<String, Object>  storage, String ipAddress, int portNumber ) {

        this.connectionSocket=connectionSocket;
        this.storage=storage;
        this.ipAddress=ipAddress;
        this.portNumber=portNumber;
    }

    @Override
    public void run() {
    	try {
        	Socket connectionSocket1 = (Socket) storage.get(ipAddress+" - "+portNumber);
            System.out.println(Thread.currentThread().getName() +" Original object:"+connectionSocket.toString()+" Shared: " + connectionSocket1.toString() );


            Random rand = new Random();
            int nxt = rand.nextInt(4);
            int sleep_time=(nxt +1) * storage.size();
            System.out.println(Thread.currentThread().getName() +"Sleep time:"+sleep_time);
            Thread.sleep( sleep_time );

            System.out.println(Thread.currentThread().getName() +" Sleep time:"+sleep_time+" IP Address of the client: " + ipAddress +":"+ portNumber);

            DataOutputStream outToClient = new DataOutputStream(connectionSocket.getOutputStream());

            String output = "DONE!";

            outToClient.writeBytes(output + "\n");

            outToClient.flush();
            outToClient.close();
        } catch (Exception e) {
        	System.out.println(Thread.currentThread().getName() +":"+connectionSocket.toString()+" :"+e.getMessage());
        	//e.printStackTrace();

        } finally {
            try {
                System.out.println("Closing Connection: "+Thread.currentThread().getName() +":"+connectionSocket.toString()+" IP Address of the client: " + connectionSocket.getInetAddress().getHostAddress() +":"+ connectionSocket.getPort()+":"+ connectionSocket.getRemoteSocketAddress());
                storage.remove(connectionSocket);
                connectionSocket.close();
            } catch (Exception e) {
//            	System.out.println(Thread.currentThread().getName() +" :Finally:"+e.getMessage());
                e.printStackTrace();
            }

    	}
    }
}

This snippet took 0.01 seconds to highlight.

Back to the Entry List or Home.

Delete this entry (admin only).