Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert client-server chat application running on command prompt into web based application?

I have made a mutiple client- server chat application using socket programming, which I can deploy on command prompt as JAR files. Now what I have to make changes to run this application on web browser using tomcat server?

My code for server:

package com.Aricent;

import java.io.DataInputStream;
import java.io.IOException;
import java.io.PrintStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.sql.*;
import java.sql.DriverManager;

public class Server {

    static ServerSocket serverSocket=null;
    static Socket clientSocket=null;
    static final int max=20;
    static clientThread[] threads=new clientThread[max];
    public static void main(String arg[])
    {
        int portNumber=2222;
        try{
        serverSocket=new ServerSocket(portNumber);
        }catch(IOException e)
        {
            System.out.println(e);
        }

        while(true)
        {
            try{
                clientSocket=serverSocket.accept();
                int i=0;
                for(i=0;i<max;i++)
                {
                    if(threads[i]==null)// searching for empty position
                    {
                        (threads[i]=new clientThread(clientSocket, threads)).start();
                        break;
                    }
                }
                if(i==max)
                {
                    PrintStream os=new PrintStream(clientSocket.getOutputStream());
                    os.println("Server too busy. Try later");
                    os.close();
                    clientSocket.close();
                }
            }catch(IOException e)
            {
                System.out.println(e);
            }
        }
    }

}


class clientThread extends Thread
{
    String clientName=null;
    DataInputStream is=null;
    PrintStream os=null;
    Socket clientSocket=null;
    clientThread[] threads;
    int max;
    String dbPath="jdbc:mysql://172.19.24.66:3306/chatdb";
    String dbUser="root";
    String dbPass="root";

    public clientThread(Socket clientSocket, clientThread[] threads)
    {
        this.clientSocket=clientSocket;
        this.threads=threads;
        max=threads.length;
    }

    public void run()
    {

        int max=this.max;
        clientThread[] threads=this.threads;
        boolean choice=false;
        String sender="";



        try{
            Class.forName("com.mysql.jdbc.Driver");
            Connection con=DriverManager.getConnection(dbPath,dbUser,dbPass);
            PreparedStatement ps=null;
            ResultSet rs=null;
            Statement stmt=con.createStatement();
            String query="";


            is=new DataInputStream(clientSocket.getInputStream());
            os=new PrintStream(clientSocket.getOutputStream());
            String name="";
            String ch="";
            boolean login=false;
            while(!login)
            {
                os.println("*** Press 1 to login or press 2 to register***");
                ch=is.readLine();
                os.println(ch);
                if(ch.equals("1"))
                {
                    os.println("Enter your username and password...");
                    String uname=is.readLine();
                    String upass=is.readLine();
                    query="Select * from user where username= '"+uname+"' and password= '"+upass+"'";
                    rs=stmt.executeQuery(query);
                    if(rs.next() && !rs.getString("status").equals("online"))
                    {
                        query="update user set status='online' where username='"+uname+"'";
                        stmt.executeUpdate(query);
                        login=true;
                        name=uname;
                    }
                    else
                        os.println("Sorry wrong credentials");
                }
                else if(ch.equals("2"))
                {
                    os.println("Enter your username and password and emailId for registration...");
                    String uname=is.readLine();
                    String upass=is.readLine();
                    String uemail=is.readLine();
                    query="Select username from user where emailId= '"+uemail+"'";
                    rs=stmt.executeQuery(query);
                    if(rs.next() )
                    {
                        os.println("Sorry user- "+rs.getString("username")+" already registered with this mail id");

                    }
                    else
                    {
                        query="insert into user (username,password,emailId,status) value('"+uname+"','"+upass+"','"+uemail+"','offline')";
                        stmt.executeUpdate(query);
                        os.println("Registration successful...");
                    }
                }
                else
                    os.println("Wrong input");
            }






            os.println("Welcome "+ name+" to chat room. \n To leave enter: /stop \n To start private chat enter: /Private USERNAME YOUR MESSAGE \n To stop private chat enter: /endPrivate");
            synchronized(this){
                for(int i=0;i<max;i++)
                {
                    if(threads[i]!=null && threads[i]==this){
                        clientName=name;
                        break;
                    }
                }

                for(int i=0;i<max;i++)
                {
                    if(threads[i]!=null&& threads[i]!=this)
                    {
                        threads[i].os.println("*NEW USER "+name+" ENTERed CHAT ROOM*");

                    }
                }
            }

            while(true)
            {
                int pos=0;
                String line=is.readLine();
                if(line.startsWith("/stop"))
                {
                    break;
                }
                if(line.startsWith("/endPrivate"))
                {
                    choice=false;

                }
                if(line.startsWith("/Private") || choice==true )
                {
                    choice=true;
                    //String words[];
                    if(line.startsWith("/Private"))
                    {
                        //pos=2;
                         String words[]=line.split("\\s",3);
                         sender=words[1];
                        synchronized(this)
                        {
                            for(int i=0;i<max;i++)
                            {
                                if(threads[i]!=null && threads[i]!=this && threads[i].clientName.equals(words[1]) )
                                {
                                    threads[i].os.println("<"+name+">"+words[2]);
                                    this.os.println(">>"+name+" "+words[2]); //showing the sender that msg is sent
                                    break;
                                }
                            }
                        }

                    }
                    else
                    {
                    String words[]=line.split("\\s",1);
                    synchronized(this)
                    {
                        for(int i=0;i<max;i++)
                        {
                            if(threads[i]!=null && threads[i]!=this && threads[i].clientName.equals(sender) )
                            {
                                threads[i].os.println("<"+name+">"+words[0]);
                                this.os.println(">>"+name+" "+words[0]); //showing the sender that msg is sent
                                break;
                            }
                        }
                    }
                    }
                    }
                else
                {
                    synchronized(this){
                        for(int i=0;i<max;i++)
                        {
                            if(threads[i]!=null  && threads[i].clientName!=null )
                            {
                                threads[i].os.println("< "+name+" > "+line);
                                //threads[i].os.println("** The user "+name+" is leaving the chat room **");
                            }
                        }

                    }
                }
            }

            //after while
            synchronized(this)
            {
                for(int i=0;i<max;i++)
                {
                    if(threads[i]!=null  && threads[i].clientName!=null )
                    {

                        threads[i].os.println("** The user "+name+" is leaving the chat room **");
                    }
                }
            }
                    os.println("** Bye "+name+" **");

                    synchronized(this)
                    {
                        for(int i=0;i<max;i++)
                        {
                            if(threads[i]==this)
                            {
                                threads[i]=null;
                            }




                }


            }
                    is.close();
                    os.close();
                    clientSocket.close();





        }catch(Exception e)
        {
            System.out.println(e);
        }




    }

}

Code for client:

package com.Aricent;

import java.io.*;
import java.net.*;

public class Client implements Runnable {

    static Socket clientSocket=null;
    static PrintStream os=null;
    static DataInputStream is=null;
    static BufferedReader inputLine=null;
    static boolean closed=false;

    public static void main(String arg[])
    {
        int portNumber=2222;
        String host="localhost";

        try{
            clientSocket=new Socket(host,portNumber);
            inputLine=new BufferedReader(new InputStreamReader(System.in));
            os=new PrintStream(clientSocket.getOutputStream());
            is=new DataInputStream(clientSocket.getInputStream());

        }
        catch(Exception e)
        {
            System.out.println(e);
        }

        if(clientSocket!=null&&os!=null&&is!=null)
        {
            try{
                new Thread(new Client()).start();
                while(!closed)
                {
                    os.println(inputLine.readLine().trim());
                }
                os.close();
                is.close();
                clientSocket.close();
            }catch(IOException e)
            {
                System.out.println(e);
            }
        }

    }





    //@Override
    public void run() {
        // TODO Auto-generated method stub

        String responseLine;
        try{
            while((responseLine=is.readLine())!=null)
            {
                System.out.println(responseLine);
                if(responseLine.indexOf("*** Bye")!=-1)
                    break;
            }
            closed=true;
        } catch(Exception e)
        {
            System.out.println(e);
        }

    }


}

My main query is how to introduce socket programming in local tomcat server?

like image 846
dexter Avatar asked May 16 '16 12:05

dexter


1 Answers

I posted the complete solution few years ago, but it uses nodejs for server. Building a chat app that uses a node.js server in IOS. This app uses server push technology (web sockets).

If you would like to migrate your current code is the browser as it is, you will have few weeks of work only with adapting the server thread to work with HTTP from the browser. Browsers communicate with servers via HTTP protocol, which is one layer above your current solution. Your solution is using plain network sockets.

You can however build a long polling type of application with servlets on Tomcat and normal web application that repeatedly checks server for new chat messages (new request every few seconds), or experiment with latest Tomcat's Websocket support. There is example chat application in Tomcat's samples. Download zip, see /apache-tomcat-8.0.35/webapps/examples/websocket/.

like image 77
Mitja Gustin Avatar answered Oct 11 '22 09:10

Mitja Gustin