Results 1 to 20 of 20
  1. #1
    mrhid6 is offline Member
    Join Date
    Sep 2011
    Posts
    37
    Rep Power
    0

    Default Out of memory sockets and thread?

    ok so i have a server and a client and the client has to send and request data to the sever but the server soon becomes out of memory here is server code.. basically i have set the vm to -Xms16m -Xms1024m but it still want to go over that how can i get the memory down

    Java Code:
    import java.net.*; 
    import java.io.*;
    import javax.swing.*;
    
    public class EchoServer extends Thread
    {         
        ServerSocket m_ServerSocket; 
        Mysql db;
        public boolean stopped = false;
        public String returntext = "";
    
        public void run()  
        { 
            startserver();
            return;
        }
    
        public void startserver(){
    
            db=new Mysql();
            try  
            { 
                // Create the server socket. 
                m_ServerSocket = new ServerSocket(12111); 
            } 
            catch(IOException ioe) 
            { 
                System.out.println("Could not create server socket at 12111. Quitting."); 
                System.exit(-1); 
            } 
            System.out.println("Listening for clients on 12111"); 
            int id = 0; 
            while(stopped!=true) 
            {                         
                try 
                { 
                    // Accept incoming connections. 
                    Socket clientSocket = m_ServerSocket.accept(); 
    
                    // accept() will block until a client connects to the server. 
                    // If execution reaches this point, then it means that a client 
                    // socket has been accepted. 
    
                    // For each client, we will start a service thread to 
                    // service the client requests. This is to demonstrate a 
                    // multithreaded server, although not required for such a 
                    // trivial application. Starting a thread also lets our 
                    // EchoServer accept multiple connections simultaneously. 
    
                    // Start a service thread 
    
                    ClientServiceThread cliThread = new ClientServiceThread(clientSocket, id++); 
                    cliThread.start(); 
                } 
                catch(IOException ioe) 
                { 
                    System.out.println("Exception encountered on accept. Ignoring. Stack Trace :"); 
                    ioe.printStackTrace(); 
                } 
            } 
        }
    
        public void stopserver(){
            stopped = true;
            m_ServerSocket = null;
            System.exit(0); 
        }
    
        public static void main (String[] args) 
        { 
            new EchoServer();     
        } 
    
        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() 
            {       
                // Obtain the input stream and the output stream for the socket 
                // A good practice is to encapsulate them with a BufferedReader 
                // and a PrintWriter as shown below. 
                BufferedReader in = null;  
                PrintWriter out = null; 
    
                // Print out details of this connection 
                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())); 
    
                    // At this point, we can read for input and reply with appropriate output. 
    
                    // Run in a loop until m_bRunThread is set to false 
                    while(m_bRunThread && in!=null) 
                    {                     
                        // read incoming stream 
                        String clientCommand = in.readLine(); 
                        //System.out.println(clientCommand);
                        String[] msg = clientCommand.split(",");
    
                        String temp_cmd1 = msg[0];
                        String[] temp_cmd2 = temp_cmd1.split("=");
                        String cmd = temp_cmd2[1];
    
                        if(cmd.equalsIgnoreCase("quit")) 
                        { 
                            // Special command. Quit this thread 
                            m_bRunThread = false;    
                            System.out.print("Stopping client thread for client : " + m_clientID); 
                        }
                        if(cmd.equalsIgnoreCase("login")){
    
                            String[] temp_uname = msg[1].split("=");
                            String uname = temp_uname[1];
    
                            String[] temp_pass = msg[2].split("=");
                            String pwd = temp_pass[1];
                            //out.println(uname+":"+pass);
                            //out.flush();
                            System.out.println("Client " + m_clientID +" Says :" + cmd+" user:"+uname); 
                            int taskman = db.loginplayer(uname,pwd);
                            if(taskman>0){
                                out.println("cmd=loginsuc,pid="+taskman);
                                out.flush();
                            }else{
                                out.println("cmd=loginfail");
                                out.flush();
                            }
    
                        }
                        if(cmd.equalsIgnoreCase("logout")){
                            System.out.println("Client " + m_clientID +" Says :" + cmd); 
                            String[] temp_pid = msg[1].split("=");
                            int playerid = Integer.parseInt(temp_pid[1]);
                            db.logoutuser(playerid);
                            m_bRunThread=false;
                            in.close();
                            out.close();
                            m_clientSocket.close();
    
                        }
                        if(cmd.equalsIgnoreCase("getplayerdata")){
                            System.out.println("Client " + m_clientID +" Says :" + cmd); 
    
                            String[] temp_pid = msg[1].split("=");
                            int playerid = Integer.parseInt(temp_pid[1]);
    
                            out.println(db.getplayerdata(playerid));
                            out.flush();
    
                        }
                        if(cmd.equalsIgnoreCase("onlineplayers")){
                            //System.out.println("Client " + m_clientID +" Says :" + cmd); 
                            String[] temp_pid = msg[1].split("=");
                            int pid = Integer.parseInt(temp_pid[1]);
    
                            String[] temp_mapid = msg[2].split("=");
                            int mapid = Integer.parseInt(temp_mapid[1]);
    
                            String[] temp_xpos = msg[3].split("=");
                            int xpos = Integer.parseInt(temp_xpos[1]);
    
                            String[] temp_ypos = msg[4].split("=");
                            int ypos = Integer.parseInt(temp_ypos[1]);
    
                            db.updateplayerpos(xpos,ypos,pid);
                            out.println(db.getonlineplayer(mapid,pid));
                            out.flush();
                        }
    
                    } 
                } 
                catch(Exception e) 
                { 
                    //e.printStackTrace(); 
                } 
                finally 
                { 
                    // Clean up 
                    try 
                    {                     
                        in.close(); 
                        out.close(); 
                        m_bRunThread=false;
                        m_clientSocket.close(); 
                        System.out.println(" Client : ID - " + m_clientID +"...Stopped"); 
                    } 
                    catch(IOException ioe) 
                    { 
                        ioe.printStackTrace(); 
                    } 
                } 
            }
        } 
    }

  2. #2
    doWhile is offline Moderator
    Join Date
    Jul 2010
    Location
    California
    Posts
    1,641
    Rep Power
    7

    Default Re: Out of memory sockets and thread?

    How many clients are connecting? What is Mysql (I presume its a database delegate class?)? What sort of operations does Mysql perform? FWIW, its better practice to implement Runnable rather than extend thread, as well as somehow log the Exceptions (there is an Exception caught and not dealt with whatsoever).

  3. #3
    mrhid6 is offline Member
    Join Date
    Sep 2011
    Posts
    37
    Rep Power
    0

    Default Re: Out of memory sockets and thread?

    there is unlimited amount of clients connecting, the mysql is getting stuff from the database i have to make it thread becuase of the gui connected with it. here is code for mysql..
    Java Code:
    import java.sql.*;
    public class Mysql{
        Connection con;
        PreparedStatement pst;
        Statement state;
        ResultSet rs;
        private int updateticker = 0;
    
        Mysql(){
            try{
                Class.forName("com.mysql.jdbc.Driver");
                con=DriverManager.getConnection("jdbc:mysql://localhost:3306/zombies","gameserver","game@server");
            }catch(Exception e){
                System.out.println(e);
            }
        }
    
        public void mysql_close(){
            try{
                con.close();
            }catch(Exception e){
                System.out.println(e);
            }
        }
    
        public int loginplayer(String uname, String pwd){
            try{
                pst = con.prepareStatement("select * from players where uname='"+uname+"' AND pass='"+pwd+"'");
                rs = pst.executeQuery();
    
                if(rs.next()){
                    pst=con.prepareStatement("update players set online='1' where uname='"+uname+"'");
                    pst.executeUpdate();
                    int id = rs.getInt("ID");
                    return id;
                }else{
                    return 0;   
                }
            }catch(Exception e){
                System.out.println("["+uname+"]Login error while vaidation "+e);
                return 0;
            }
        }
    
        synchronized public void updateplayerpos(int x,int y,int pid){
            if(x>0 && y>0 && pid!=0){
                try{
                    pst = con.prepareStatement("select * from players where ID='"+pid+"'");
                    rs = pst.executeQuery();
    
                    if(rs.next() && rs!=null){
                        int currentx = rs.getInt("xpos");
                        int currenty = rs.getInt("ypos");
    
                        if(x==currentx && y==currenty){
    
                        }else{
                            pst=con.prepareStatement("update players set xpos='"+x+"',ypos='"+y+"' where ID='"+pid+"'");
                            pst.executeUpdate();
                        }
                    }
                    rs=null;
                }catch(Exception e){
                    System.out.println("["+pid+"]Update Player Error While Validating "+e);
                }
            }
        }
    
        public String getplayerdata(int pid){
            String returnstring ="";
            if(pid!=0){
                try{
                    pst = con.prepareStatement("select * from players where ID='"+pid+"'");
                    rs = pst.executeQuery();
                    if(rs.next()){
                        returnstring = "username="+rs.getString("uname")+
                        ",xpos="+rs.getInt("xpos")+",ypos="+rs.getInt("ypos")+",gender="+rs.getString("gender")+",areaid="+rs.getInt("areaid");
    
                    }
                    rs=null;
                }catch(Exception e){
                    System.out.println("["+pid+"]Player Data Error While Validating "+e);
                }
            }
            return returnstring;
        }
    
        synchronized public String getonlineplayer(int mapid,int pid){
            String returnstring ="";
            if(mapid>0 && pid!=0){
                try{
                    pst = con.prepareStatement("select * from players where areaid='"+mapid+"' and online='1' and ID!='"+pid+"'",ResultSet.TYPE_SCROLL_INSENSITIVE,ResultSet.CONCUR_READ_ONLY);
                    rs = pst.executeQuery();
                    rs.beforeFirst();
                    while(rs.next()){
    
                        String uname = rs.getString("uname");
                        int pimage = rs.getInt("playerimage");
                        int  xpos = rs.getInt("xpos");
                        int ypos = rs.getInt("ypos");
    
                        returnstring += "username="+uname+
                        ",xpos="+Integer.toString(xpos)+",ypos="+Integer.toString(ypos)+",playerimage="+Integer.toString(pimage)+"#";
                    }
                    rs=null;
                }catch(Exception e){
                    e.printStackTrace();
                    System.out.println("["+pid+"]Online Players Error While Validating "+e);
                }
            }
            return returnstring;
        }
    
        public void logoutuser(int pid){
            try{
                pst=con.prepareStatement("update players set online='0' where ID='"+pid+"'");
                pst.executeUpdate();
                rs=null;
            }catch(Exception e){
                System.out.println("["+pid+"]Logout Error While Validating "+e);
            }
        }
    }

  4. #4
    doWhile is offline Moderator
    Join Date
    Jul 2010
    Location
    California
    Posts
    1,641
    Rep Power
    7

    Default Re: Out of memory sockets and thread?

    A quick glance and I do not see anything that would cause an OutOfMemoryException (perhaps someone else will come along and spot something). That being said, the code does have a lot things that should be done, like closing the result sets,preparedStatements and database Connection; using PreparedStatement properly; and...

    i have to make it thread becuase of the gui connected with it.
    I will say it again...implement Runnable rather than extend thread. See
    Defining and Starting a Thread (The Java™ Tutorials > Essential Classes > Concurrency)
    But again, I doubt any of these changes will help with the exception. By the way...did you set -Xmx? You original post lists both settings as -Xms

  5. #5
    mrhid6 is offline Member
    Join Date
    Sep 2011
    Posts
    37
    Rep Power
    0

    Default Re: Out of memory sockets and thread?

    Quote Originally Posted by doWhile View Post
    A quick glance and I do not see anything that would cause an OutOfMemoryException (perhaps someone else will come along and spot something). That being said, the code does have a lot things that should be done, like closing the result sets,preparedStatements and database Connection; using PreparedStatement properly; and...

    I will say it again...implement Runnable rather than extend thread.
    But again, I doubt any of these changes will help with the exception. By the way...did you set -Xmx? You original post lists both settings as -Xms
    forgot to say that the client has a thread that is constantly sending data to socket server and no i haven't set Xmx how u set it?

  6. #6
    doWhile is offline Moderator
    Join Date
    Jul 2010
    Location
    California
    Posts
    1,641
    Rep Power
    7

    Default Re: Out of memory sockets and thread?

    no i haven't set Xmx how u set it?
    Your original post stated using -Xms, which sets the small size of the heap. Set the maximum heap size using the -Xmx JVM option (google for how to use this)

  7. #7
    mrhid6 is offline Member
    Join Date
    Sep 2011
    Posts
    37
    Rep Power
    0

    Default Re: Out of memory sockets and thread?

    ok i have set it and the problem is still the same ? is there anyway of clearing the heap data one the server reads the inputstream? or something simular?

  8. #8
    doWhile is offline Moderator
    Join Date
    Jul 2010
    Location
    California
    Posts
    1,641
    Rep Power
    7

    Default Re: Out of memory sockets and thread?

    Quote Originally Posted by mrhid6 View Post
    is there anyway of clearing the heap data one the server reads the inputstream? or something simular?
    Its called garbage collection, it is done by the Garbage Collector, and there is no reason invoke it directly.

    Post the code of your client, or preferably a stripped down (SSCCE) version that still gives the behavior you receive.

  9. #9
    mrhid6 is offline Member
    Join Date
    Sep 2011
    Posts
    37
    Rep Power
    0

    Default Re: Out of memory sockets and thread?

    Well the client has functions to it and sends it to the server the stuff it send to server are like this "cmd=login,user=u,pass=p" the function called the most is the onlineplayers function it is called inside a thread in an while loop as i am making a mmorpg it has to get onlineplayers all the time so has to be called all the time

  10. #10
    doWhile is offline Moderator
    Join Date
    Jul 2010
    Location
    California
    Posts
    1,641
    Rep Power
    7

    Default Re: Out of memory sockets and thread?

    Once again, post an SSCCE of the client that reproduce the problem.

  11. #11
    AndyVidk is offline Member
    Join Date
    Oct 2011
    Posts
    13
    Rep Power
    0

    Default Re: Out of memory sockets and thread?

    Quote Originally Posted by mrhid6 View Post
    Well the client has functions to it and sends it to the server the stuff it send to server are like this "cmd=login,user=u,pass=p" the function called the most is the onlineplayers function it is called inside a thread in an while loop as i am making a mmorpg it has to get onlineplayers all the time so has to be called all the time
    If i understand this statement correctly would it not be more efficient to implements an observer pattern?

  12. #12
    mrhid6 is offline Member
    Join Date
    Sep 2011
    Posts
    37
    Rep Power
    0

    Default Re: Out of memory sockets and thread?

    so how could i make the observer pattern work with my set up?

  13. #13
    doWhile is offline Moderator
    Join Date
    Jul 2010
    Location
    California
    Posts
    1,641
    Rep Power
    7

    Default Re: Out of memory sockets and thread?

    FWIW I have no idea how implementing Observable addresses the issue at hand, or how one can advice to do so without seeing the client code itself. Your mileage may vary however.

  14. #14
    AndyVidk is offline Member
    Join Date
    Oct 2011
    Posts
    13
    Rep Power
    0

    Default Re: Out of memory sockets and thread?

    Quote Originally Posted by mrhid6 View Post
    so how could i make the observer pattern work with my set up?
    Well, if you have a server with all the players registered. You can have an on-server event that triggers a method on the server that will transmit an event too all players.The player should implement some sort of event listener. The event should indicate that some change has occurred, and then the player can have a method to update that which needs updating. I don't know if i explain this thoroughly but i think its the essence.

    I don't know if this is the case but: Its never a good idea to have an infinite loop.


    EDIT: Never mind, i think i misunderstood the question at hand.

    Regards Andy.
    Last edited by AndyVidk; 10-10-2011 at 10:28 AM.

  15. #15
    mrhid6 is offline Member
    Join Date
    Sep 2011
    Posts
    37
    Rep Power
    0

    Default Re: Out of memory sockets and thread?

    So is there any other ideas on how to fix my problem?

  16. #16
    doWhile is offline Moderator
    Join Date
    Jul 2010
    Location
    California
    Posts
    1,641
    Rep Power
    7

    Default Re: Out of memory sockets and thread?

    Quote Originally Posted by mrhid6 View Post
    So is there any other ideas on how to fix my problem?
    Evidently you are completely ignoring all of my posts above, so I will say this one more time, after which I will stop wasting my time - post an SSCCE of the client code.

  17. #17
    mrhid6 is offline Member
    Join Date
    Sep 2011
    Posts
    37
    Rep Power
    0

    Default Re: Out of memory sockets and thread?

    ok so this is the client script the client is called on a class called players it then in a thread it calls both getonlinelayer() and updateplayerpos() these are in a while loop

    Java Code:
    import java.net.*; 
    import java.io.*; 
    
    // A client for our multithreaded EchoServer. 
    public class Client 
    { 
        BufferedReader in = null; 
        PrintWriter out = null; 
        Socket s = null; 
        public Client()
        { 
    
            // Create the socket connection to the EchoServer. 
            try 
            { 
    
                s = new Socket("webserver.xorbo.com", 12111); 
            }         
            catch(UnknownHostException uhe) 
            { 
                // Host unreachable 
                System.out.println("Unknown Host :" + "localhost"); 
                s = null; 
            } 
            catch(IOException ioe) 
            { 
                // Cannot connect to port on given host 
                System.out.println("Cant connect to server at 12111. Make sure it is running."); 
                s = null; 
            } 
    
            if(s == null) 
                System.exit(-1);
    
            try 
            { 
                // Create the streams to send and receive information 
                in = new BufferedReader(new InputStreamReader(s.getInputStream())); 
                out = new PrintWriter(new OutputStreamWriter(s.getOutputStream())); 
    
            } catch(IOException ioe) 
            { 
                System.out.println("Exception during communication. Server probably closed connection."); 
            } 
        } 
    
        public int loginuser(String uname, String pwd){
            try 
            { 
    
                // Since this is the client, we will initiate the talking. 
                // Send a string. 
                out.println("cmd=login,user="+uname+",pass="+pwd); 
                out.flush(); 
                // receive the reply. 
    
                String serverReply = in.readLine();
                System.out.println("Server Says : " + serverReply); 
    
                String[] temp_rpy = serverReply.split(",");
                String[] temp_cmd = temp_rpy[0].split("=");
                String cmd = temp_cmd[1];
    
                if(cmd.equals("loginsuc")){
                    String[] temp_pid = temp_rpy[1].split("=");
                    int pid = Integer.parseInt(temp_pid[1]);
    
                    return pid ;
                }else{
                    return 0 ;
                }
    
                //out.println("cmd=quit"); 
                //out.flush();
            } 
            catch(IOException ioe) 
            { 
                System.out.println("Exception during communication. Server probably closed connection."); 
            } 
            return 0;
        }
    
        public String getonlineplayers(int mapid,int pid){
            try 
            { 
                // Since this is the client, we will initiate the talking. 
                // Send a string. 
                out.println("cmd=onlineplayers,pid="+pid+",mapid="+mapid); 
                out.flush(); 
                // receive the reply. 
    
                String serverReply = in.readLine();
                //System.out.println("Server Says : " + serverReply); 
                return serverReply;
    
                //out.println("cmd=quit"); 
                //out.flush();
            } 
            catch(IOException ioe) 
            { 
                //System.out.println("Connection Failed"); 
            } 
            return"";
        }
    
        public void updateplayerpos(int x, int y,int pid){
            // Since this is the client, we will initiate the talking. 
            // Send a string. 
            out.println("cmd=updatePpos,playerid="+pid+",xpos="+x+",ypos="+y); 
            out.flush(); 
    
            //out.println("cmd=quit"); 
            //out.flush();
        }
    
        public String getPlayerData(int pid){
            String returndata = "";
            try 
            { 
    
                // Since this is the client, we will initiate the talking. 
                // Send a string. 
                out.println("cmd=getplayerdata,playerid="+pid); 
                out.flush(); 
                // receive the reply. 
    
                String serverReply = in.readLine();
                System.out.println("Server Says : " + serverReply); 
    
                returndata = serverReply;
    
                //out.println("cmd=quit"); 
                //out.flush();
            } 
            catch(IOException ioe) 
            { 
                //System.out.println("Exception during communication. Server probably closed connection."); 
            } 
            return returndata ;
        }
    
        public void Clientend(int pid){
            try 
            { 
    
                // Since this is the client, we will initiate the talking. 
                // Send a string. 
                out.println("cmd=logout,playerid="+pid); 
                out.flush(); 
                // Close the streams 
                out.close(); 
                in.close(); 
                // Close the socket before quitting 
                s.close(); 
            } 
            catch(Exception e) 
            { 
                e.printStackTrace(); 
            }    
        }
    
        public void loginexit(){
            try 
            { 
                // Since this is the client, we will initiate the talking. 
                // Send a string. 
                out.println("cmd=quit"); 
                out.flush(); 
                // Close the streams 
                out.close(); 
                in.close(); 
                // Close the socket before quitting 
                s.close(); 
            } 
            catch(Exception e) 
            { 
                e.printStackTrace(); 
            }    
        }
    }

  18. #18
    mrhid6 is offline Member
    Join Date
    Sep 2011
    Posts
    37
    Rep Power
    0

    Default Re: Out of memory sockets and thread?

    ok so doing some troubleshooting i have found that it is to do with my database code if anyone can help see y it uses up lots of memory would be great

  19. #19
    doWhile is offline Moderator
    Join Date
    Jul 2010
    Location
    California
    Posts
    1,641
    Rep Power
    7

    Default Re: Out of memory sockets and thread?

    Read my second response above: close your ResultSet and PreparedStatement's when you are finished with them. Following best practices, this should be done in the finally portion of try/catch, or use a PreparedStatement correctly and - rather than recreate it each time - create it once and set its parameters and close it within the close() method.

  20. #20
    mrhid6 is offline Member
    Join Date
    Sep 2011
    Posts
    37
    Rep Power
    0

    Default Re: Out of memory sockets and thread?

    Ok yay it is now stable and is maintaining approx 37mb i had missed the 'finally' bit off the mysql thanks doWhile :) thanks for your time and help

Similar Threads

  1. Replies: 1
    Last Post: 07-18-2011, 04:24 PM
  2. Sockets
    By PhQ in forum New To Java
    Replies: 1
    Last Post: 05-04-2010, 03:36 AM
  3. Replies: 6
    Last Post: 11-18-2009, 11:39 PM
  4. Replies: 2
    Last Post: 08-21-2008, 07:33 PM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •