Wednesday, September 24, 2014

JAVA Server Socket Server & Client Program

Following code can be used to run a server socket application. This socket application listen requests on "locathost" port "10225" .

Socket Server Program

public class SocketServer {

    ServerSocket m_ServerSocket;
    Logger logger;
    int SERVER_PORT = 10225;

    public SocketServer() {
        try {
            m_ServerSocket = new ServerSocket(SERVER_PORT);
        } catch (IOException ioe) {
            System.out.println("Could not create server socket " + SERVER_PORT + " Quitting. " + ioe);
            System.exit(-1);
        }
        int id = 0;
        while (true) {
            try {
                Socket clientSocket = m_ServerSocket.accept();
                ClientServiceThread cliThread = new ClientServiceThread(clientSocket, id++);
                cliThread.start();
            } catch (Exception ioe) {
                System.out.println("Constructor : " + ioe);
            }
        }
    }

    public String process(String input) {
        String response = "";
        // your process logic
        return response;
    }

    class ClientServiceThread extends Thread {

        Socket m_clientSocket;
        int m_clientID = -1;
        boolean m_bRunThread = true;

        ClientServiceThread(Socket s, int clientID) {
            m_clientSocket = s;
            m_clientID = clientID;
        }

        public void run() {
            BufferedReader in = null;
            PrintWriter out = null;
            System.out.println("Accepted Client ID - " + m_clientID + " |Address - " + m_clientSocket.getInetAddress().getHostName());

            try {
                in = new BufferedReader(new InputStreamReader(m_clientSocket.getInputStream()));
                out = new PrintWriter(new OutputStreamWriter(m_clientSocket.getOutputStream()));

                while (m_bRunThread) {
                    String clientCommand = in.readLine();
                    System.out.println("Client Says :" + clientCommand);
                    if (!clientCommand.equalsIgnoreCase("Quit")) {
                        out.println(process(clientCommand));
                    }
                    if (clientCommand.equalsIgnoreCase("quit")) {
                        m_bRunThread = false;
                    } else {
                        out.flush();
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                try {
                    in.close();
                    out.close();
                    m_clientSocket.close();
                    System.out.println("...Stopped");
                } catch (IOException ioe) {
                    System.out.println("ClientServiceThread.run " + ioe);
                }
            }
        }
    }

    public static void main(String[] args) {
        new ChargeSocket();
    }
}

Socket Client Program

    public String connectToSocket(String ip, int port, String request) {
        String response = null;
        Socket socket = null;
        try {
            socket = new Socket(ip, port);
        } catch (UnknownHostException unknownhostexception) {
            System.out.println("Unknown Host :localhost");
            socket = null;
        } catch (IOException ioexception) {
            System.out.println("Cant connect to server at " + ip + " " + port + " Make sure it is running.");
            socket = null;
        }
        if (socket == null) {
            return null;
        }
        BufferedReader bufferedreader = null;
        PrintWriter printwriter = null;
        try {
            bufferedreader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
            printwriter = new PrintWriter(new OutputStreamWriter(socket.getOutputStream()));
            printwriter.println(request);
            printwriter.flush();
            response = bufferedreader.readLine();
            System.out.println("Server Says : " + response);
            printwriter.println("Quit");
            printwriter.flush();
        } catch (IOException ioexception) {
            System.out.println("Exception during communication. Server probably closed connection.");
            ioexception.printStackTrace();
        } finally {
            try {
                printwriter.close();
                bufferedreader.close();
                socket.close();
            } catch (Exception exception1) {
                exception1.printStackTrace();
            }
        }
        return response;

    }