Solved

Server program response in 15 second!

Posted on 2004-10-20
7
246 Views
Last Modified: 2011-09-20
Dear All !
hi
I'd made a client/server program that clients get some information from server (server gathers this information from user's profile stored in MySQL) the problem is raise because of 15 sec takes to get a simple response from server program to a client , I tested it on a LAN with 3 computer and very very low traffic(almost zero) , then could you help me to improve it in a way responsing sooner, i forgot to tell i user JAVA ,MySQL on windows!
here is the server class


package net.xagrose.officeSrv;

import java.net.*;
import java.io.*;
import java.sql.*;
import java.util.Date;
import net.xagrose.officeLocalClass.*;
import net.xagrose.socket.*;
import net.xagrose.Authentication.*;
import net.xagrose.DB.*;



public class NetworkServer {
  protected int port, maxConnections;
    ObjectOutputStream output;
    ObjectInputStream input;
    Carrier msgCr;
    private String SQLstr;




  public NetworkServer(int port, int maxConnections) {
    this.port = port;
    this.maxConnections = maxConnections;
  }



  public void listen() {
    int i=0;
    try {
      ServerSocket listener = new ServerSocket(port,100);

      Socket server;
      while    (maxConnections == 0) {
        server = listener.accept();
          server.setSoTimeout(5000);
        handleConnection(server);
      }
    } catch (IOException ioe) {
      System.err.println("NetworkServer|listen:" + ioe);

    }
  }



  protected void handleConnection(Socket server)  throws IOException{

    SocketUtil s = new SocketUtil(server);
    input=s.getInObjectStream();
    output=s.getOutObjectStream();
    System.out.println("Generic Network Server:\n" + "got connection from " + server.getInetAddress().getHostName() + "\n" );
     switch(getMsg(input)){
          case 1:{
              loginObj userLogin=(loginObj)msgCr.getCarringObj();
              Authentication userAuth=new Authentication(userLogin.getUser_name(),userLogin.getUser_psw());
              userAuth.checkAuthentication();
              if (userAuth.isAuthentified()){
                   sendMsg("Ok!");
              } else{
                   sendMsg("No!");
              }
         break;

            }
      case 2:{
          //session started
          InsertSession((String) msgCr.getCarringObj());
        break;




      }case 3:{
          EndSession((String)msgCr.getCarringObj());

        break;

      }case 5 :{
          //*
    // ask if user have started a working session or not ,if so disable the start session and gets today date from server
    //*
          officeParameter OffParm= new officeParameter(make_persian_date(),ISsessionStarted());
          sendMsg(OffParm);
          break;
      } case 6:{
         PassChangerCarrier PCC=(PassChangerCarrier)msgCr.getCarringObj();
          loginObj LO=(loginObj)PCC.getUser();
          userProfileManager upm=new userProfileManager(LO.getUser_name(),LO.getUser_psw());

          if (upm.isUser()){
                if(upm.changePassword(PCC.getNewPass())){
                    sendMsg("Ok!");
                }else{
                    sendMsg("No!");
                }

          }else{
                sendMsg("NotUser!");
          }
          break;
      }




      }

   
    server.close();
  }
    private void InsertSession(String id){
       BaseMysql BM=new BaseMysql("office","1234","office");
       if ( BM.IntialConnection()){
           Date now=new Date();
           String SQLstr;
           SQLstr="INSERT INTO user_worktime(date,start_time,user_id) VALUES('"+ now.getYear()%100 +"-"+now.getDay()+"-"+now.getMonth()+"','"+ now.getHours() +":"+now.getMinutes()+":"+now.getSeconds()+"','"+id+"')";
           BM.ExecModify(SQLstr);
           BM.CloseConnection();

       }
    }
    private void EndSession(String id){
        BaseMysql BM=new BaseMysql("office","1234","office");
        if(BM.IntialConnection()){
           Date now=new Date();
           String SQLstr;
           SQLstr="SELECT MAX(id) FROM user_worktime WHERE user_id='"+id+"'";
           ResultSet rs=BM.ExecSelect(SQLstr);
           if (rs!=null){
               try {
                    int session_id=rs.getInt(1);
                    BM.CloseConnection();
                    BM=new BaseMysql("office","1234","office");
                    BM.IntialConnection();
                    SQLstr= "UPDATE user_worktime set end_time='"+ now.getHours() +":"+now.getMinutes()+":"+now.getSeconds()+"' WHERE id="+session_id;
                    //System.out.println(SQLstr);
                    if (BM.ExecModify(SQLstr)){
                         output.writeObject("Ok!");
                         output.flush();
                    }else{
                         output.writeObject("No!");
                         output.flush();
                    }
                   BM.CloseConnection();
               }   catch(IOException ex){
                           System.err.println(ex.toString());
               }catch(SQLException ex){
                   System.err.println(ex.toString());

               }


           }
           BM.CloseConnection();

        }

    }
    private boolean ISsessionStarted() {
        int id=0;
        boolean isStarted=false;
        BaseMysql BM=new BaseMysql("office","1234","office");
        if (BM.IntialConnection()){
            String username=(String) msgCr.getCarringObj();
            SQLstr= "SELECT MAX(id) FROM user_worktime where user_id='"+ username + "'";
            ResultSet rs=BM.ExecSelect(SQLstr);
            if( rs!=null){
                try{
                    id=rs.getInt(1);
                    if (id==0){return false;}
                    BM.CloseConnection();
                    BM=new  BaseMysql("office","1234","office");
                }catch(SQLException ex){
                     isStarted=false;
                }
                     if (BM.IntialConnection()){
                          SQLstr="SELECT end_time FROM user_worktime where id="+ id;
                          rs=BM.ExecSelect(SQLstr);
                          if (rs!=null){
                              try{
                                  if(rs.getTime(1).toString().equals("00:00:00")||(rs.getTime(1)==null)){
                                      isStarted=true;
                                  }
                              }catch(SQLException ex){
                                      isStarted=false;
                                  }
                              }else{
                                       isStarted=true;
                              }
                         }
                }else{

                    isStarted=false;
                }
            }
        return isStarted;
    }
    private String make_persian_date(){
        return "Persian Date";
    }
    protected void sendMsg(Object msgTxt){
        try{
            output.writeObject(msgTxt);
            output.flush();
        }catch(IOException ex){
          System.err.println("NetworkServer:"+ex.toString());
        }
    }
    protected int getMsg(ObjectInputStream in ){
        try{
         msgCr=(Carrier)in.readObject();
         if (msgCr.getCommand().equals("Login!")){
             return 1;


         }else if (msgCr.getCommand().equals("StartSession!")){
             return 2;
         //here it start a session for given user
         }else if (msgCr.getCommand().equals("EndSession!")){
             return 3;
             //here it finish the session for given user
         }else if (msgCr.getCommand().equals("GetTotalTime!")){
             return 4;
             //here it send total working time in a period!
         }else if (msgCr.getCommand().equals("InitailOffice!")){
             return 5;
             //here it send total working time in a period!
         }else if(msgCr.getCommand().equals("ChangePass!")){
             //here it changes user's password
             return 6;
         }





        }catch(ClassNotFoundException ex){
            System.err.println("NetworkServer:"+ex.toString());

        }catch(IOException  ex){
            System.err.println("NetworkServer:"+ex.toString());

        }


        return 0;
    }
    public void start(){
        listen();
    }

}

0
Comment
Question by:lollboy
  • 3
  • 2
7 Comments
 
LVL 8

Expert Comment

by:sigmacon
ID: 12366549
Although I personally do not know anything about the net.xagrose.* package and how it works internally, but your code seems to be creating a new database connection every time you talk to the DB. That's going to cost some time, especially if the database is running on a different computer. But I might just misinterpret how this BaseMysql class works. Also, is there a particular reason why you are transmitting Objects instead of bytes or strings? This may also affect performance. I personally cannot help more than that, because of my lack of knowledge about the package mentioned above.
0
 

Author Comment

by:lollboy
ID: 12372001
I make a package net.xagrose and use it! then BaseMysql class is for MySql connection handler and in this package I keep some transfering object (through Network) and also I used objects for transfering because of different type of data I want to transfer through network and I think it's better to use serilaized objects instead of using XML (because of low speed of XML)
 
 above u mentioned that making connection may cause it , but at least when I test it on a computer both Client and Server programms it works well but when I try to test it on sperated ones the speed goes down.
0
 
LVL 8

Expert Comment

by:sigmacon
ID: 12372405
From the code posted here, I don't think it can be determined where the problem is. Since there is other code that your wrote and relying upon, the problem might be there. Maybe it has to do with your custom protocol. Maybe there is some network specific code? Are you creating a new connection from the client for each message? How does the client find the server (by IP address or network name). How is the network name of the server looked up? Maybe that's where the client spends all the time. You may also want to log certain events on the server and then see what happens and when while a client is trying to connect.
0
Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

 
LVL 8

Expert Comment

by:sigmacon
ID: 12470402
Did you get anywhere with this - did any of my comments help?
0
 

Author Comment

by:lollboy
ID: 12519513
thanks all
I found what was the problem!
nor ip or mysql reading

I changed it by following:
instead if function connection hanling i used a thread connection handler and then in client side i keep the refrence of socket i made to connect to server
0
 

Accepted Solution

by:
modulo earned 0 total points
ID: 12860635
PAQed with points refunded (250)

modulo
Community Support Moderator
0

Featured Post

Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

Title # Comments Views Activity
find a node in VST 2 63
changeXy challenge 13 67
java  and programming certification ? 4 86
Java Loop 6 48
RIA (Rich Internet Application) tools are interactive internet applications which have many of the characteristics of desktop applications. The RIA tools typically deliver output either by the way of a site-specific browser or via browser plug-in. T…
This article is meant to give a basic understanding of how to use R Sweave as a way to merge LaTeX and R code seamlessly into one presentable document.
In this fourth video of the Xpdf series, we discuss and demonstrate the PDFinfo utility, which retrieves the contents of a PDF's Info Dictionary, as well as some other information, including the page count. We show how to isolate the page count in a…
In this seventh video of the Xpdf series, we discuss and demonstrate the PDFfonts utility, which lists all the fonts used in a PDF file. It does this via a command line interface, making it suitable for use in programs, scripts, batch files — any pl…

911 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

22 Experts available now in Live!

Get 1:1 Help Now