Solved

Server program response in 15 second!

Posted on 2004-10-20
7
248 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
Gigs: Get Your Project Delivered by an Expert

Select from freelancers specializing in everything from database administration to programming, who have proven themselves as experts in their field. Hire the best, collaborate easily, pay securely and get projects done right.

 
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

Announcing the Most Valuable Experts of 2016

MVEs are more concerned with the satisfaction of those they help than with the considerable points they can earn. They are the types of people you feel privileged to call colleagues. Join us in honoring this amazing group of Experts.

Question has a verified solution.

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

Suggested Solutions

Displaying an arrayList in a listView using the default adapter is rarely the best solution. To get full control of your display data, and to be able to refresh it after editing, requires the use of a custom adapter.
This is about my first experience with programming Arduino.
In this fifth video of the Xpdf series, we discuss and demonstrate the PDFdetach utility, which is able to list and, more importantly, extract attachments that are embedded in PDF files. It does this via a command line interface, making it suitable …
With the power of JIRA, there's an unlimited number of ways you can customize it, use it and benefit from it. With that in mind, there's bound to be things that I wasn't able to cover in this course. With this summary we'll look at some places to go…

816 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

8 Experts available now in Live!

Get 1:1 Help Now