Results 1 to 8 of 8
  1. #1
    cotarelo is offline Member
    Join Date
    Mar 2010
    Posts
    43
    Rep Power
    0

    Question Receiving data from a socket and querying database

    Hi,

    I have the following program, what it does is receive information from a socket, and when the information received matchs with a cell in a database, it performs some actions, when not, it should do nothing. The program is actually working, but, in the part that it should do nothing (else part of if (actualsituation.next()){ ) after some seconds (5 or so) it gives a exception,

    My code is:

    Java Code:
    package pdp;
    
    import java.io.*;
    import java.net.*;
    import java.sql.*;
    
    public class Main {
    
    
    	public static void main(String[] args) {
    		ServerSocket ss = null;
    		Socket s = null;
    
    		try {
    			ss = new ServerSocket(6688);
    		}
    		catch (IOException e) {
                                e.printStackTrace();
                            }
    
    		System.out.println("Listening on port 6688: " + ss);
    
    		while(true){
    			try {
    				s = ss.accept();
    				System.out.println("New connections accepted: " + s);
    				new GestorPeticion(s).start();
    				s = null;
    			}
    			catch (IOException e) {
                                e.printStackTrace();
                            }
    		}
    	}
    }
    
    class GestorPeticion extends Thread {
    	BufferedReader entrada = null;
    	Socket s;
    
    	public GestorPeticion(Socket s){
    		this.s = s;
    	}
    
        @Override
    	public void run(){
    		try{
    			entrada = new BufferedReader(new InputStreamReader(s.getInputStream()));
                            String url = "jdbc:mysql://localhost/Polant";
                            Connection con = DriverManager.getConnection(url, "root", "1234");
                               
                            
    			while (true){
    				String str = entrada.readLine();
    				System.out.println("Receiving: " + str);
                                    System.out.println("Checking if there is some policy to apply");
                                    Statement select2 = con.createStatement();
                                    ResultSet actualsituation = select2.executeQuery("SELECT ifx FROM rules WHERE ifx='"+str+"';");
    
    
                                    if (actualsituation.next()){ // rs.next() is false if nothing is found
                                       System.out.println("Lets retreive the values of the policy");
                                       select2.close();
    
    
        try {
          con = DriverManager.getConnection(url, "root", "1234");
          Statement select = con.createStatement();
          ResultSet result = select.executeQuery("SELECT * FROM rules WHERE ifx='"+str+"';");
    
    
          System.out.println("Got results:");
          while (result.next()) { // process results one row at a time
              String Nr = result.getString(1);
              int Dp = result.getInt(2);
              int At = result.getInt(3);
              int Lv = result.getInt(4);
              String Bp = result.getString(5);
              String ifx = result.getString(6);
              String whenx = result.getString(7);
    
    
    
            System.out.println("Name = "+Nr);
            System.out.println("Dparam = "+Dp);
            System.out.println("At = "+At);
            System.out.println("Lv = "+Lv);
            System.out.println("Bp = "+Bp);
            System.out.println("IF = "+ifx);
            System.out.println("WHEN = "+whenx);
    
            Socket echoSocket = null;
            PrintWriter out = null;
    
                                        select2.close();
                                        con.close();
    
                                    } else{
                                        System.out.println("No policies to implement");
                                        select2.close();
                                        con.close();
    
                                    }
                                   
    			}
    
    
    
    		}
    		catch(Exception e){
                                e.printStackTrace();
                            }
    	}
    }

    And this is the error that the console gives after some minutes when the value retrieved from the socket does not match any value in the database


    com.mysql.jdbc.exceptions.jdbc4.MySQLNonTransientC onnectionException: No operations allowed after connection closed.
    at sun.reflect.NativeConstructorAccessorImpl.newInsta nce0(Native Method)
    at sun.reflect.NativeConstructorAccessorImpl.newInsta nce(NativeConstructorAccessorImpl.java:57)
    at sun.reflect.DelegatingConstructorAccessorImpl.newI nstance(DelegatingConstructorAccessorImpl.java:45)
    at java.lang.reflect.Constructor.newInstance(Construc tor.java:532)
    at com.mysql.jdbc.Util.handleNewInstance(Util.java:40 6)
    at com.mysql.jdbc.Util.getInstance(Util.java:381)
    at com.mysql.jdbc.SQLError.createSQLException(SQLErro r.java:984)
    at com.mysql.jdbc.SQLError.createSQLException(SQLErro r.java:956)
    at com.mysql.jdbc.SQLError.createSQLException(SQLErro r.java:926)
    at com.mysql.jdbc.ConnectionImpl.checkClosed(Connecti onImpl.java:1098)
    at com.mysql.jdbc.ConnectionImpl.createStatement(Conn ectionImpl.java:2380)
    at com.mysql.jdbc.ConnectionImpl.createStatement(Conn ectionImpl.java:2362)
    at pdp.GestorPeticion.run(Main.java:61)
    What is going wrong?

    I closed all possible connections
    Last edited by cotarelo; 06-21-2010 at 07:06 PM.

  2. #2
    Norm's Avatar
    Norm is online now Moderator
    Join Date
    Jun 2008
    Location
    SW Missouri
    Posts
    17,266
    Rep Power
    25

    Default

    No operations allowed after connection closed.
    What happens if you don't close the connection?

  3. #3
    Tolls is offline Moderator
    Join Date
    Apr 2009
    Posts
    11,755
    Rep Power
    19

    Default

    How are we supposed to figure out what's wrong with that when your indentation is all over the place, and a copy-paste of the code into an IDE shows the brackets are all out of synch?

    Without seeing the actual compileable code we can't say where you're going wrong...

  4. #4
    cotarelo is offline Member
    Join Date
    Mar 2010
    Posts
    43
    Rep Power
    0

    Default

    Quote Originally Posted by Tolls View Post
    How are we supposed to figure out what's wrong with that when your indentation is all over the place, and a copy-paste of the code into an IDE shows the brackets are all out of synch?

    Without seeing the actual compileable code we can't say where you're going wrong...
    You are right. I removed part of the code on the forum editor to make it more readable, but it does not compile. I am pasting a compilable code below

    Sorry for the structure but I am a novice programmer, yet.

    What happens if you don't close the connection?
    I receive something like this :

    Checking if there is some policy to apply
    No policies to implement
    Receiving: null
    Checking if there is some policy to apply
    No policies to implement
    Receiving: null
    Checking if there is some policy to apply
    No policies to implement
    Receiving: null



    Java Code:
    package pdp;
    
    import java.io.*;
    import java.net.*;
    import java.sql.*;
    
    
    
    
    public class Main {
    
    
    	public static void main(String[] args) {
    		ServerSocket ss = null;
    		Socket s = null;
    
    		try {
    			ss = new ServerSocket(6688);
    		}
    		catch (IOException e) {
                                e.printStackTrace();
                            }
    
    		System.out.println("Listening on port 6688: " + ss);
    
    		while(true){
    			try {
    				s = ss.accept();
    				System.out.println("New connections accepted: " + s);
    				new GestorPeticion(s).start();
    				s = null;
    			}
    			catch (IOException e) {
                                e.printStackTrace();
                            }
    		}
    	}
    }
    
    class GestorPeticion extends Thread {
    	BufferedReader entrada = null;
    	Socket s;
    
    	public GestorPeticion(Socket s){
    		this.s = s;
    	}
    
        @Override
    	public void run(){
    		try{
    			entrada = new BufferedReader(new InputStreamReader(s.getInputStream()));
                            String url = "jdbc:mysql://localhost/Polant";
                            Connection con = DriverManager.getConnection(url, "root", "1234");
                               
                            
    			while (true){
    				String str = entrada.readLine();
    				System.out.println("Receiving: " + str);
                                    System.out.println("Checking if there is some policy to apply");
                                    Statement select2 = con.createStatement();
                                    ResultSet actualsituation = select2.executeQuery("SELECT ifx FROM rules WHERE ifx='"+str+"';");
    
    
                                    if (actualsituation.next()){ // rs.next() is false if nothing is found
                                       System.out.println("Lets retreive the values of the policy");
                                       select2.close();
    
    
    
                                        select2.close();
                                        con.close();
    
                                    } else{
                                        System.out.println("No policies to implement");
                                        select2.close();
                                        con.close();
    
                                    }
                                   
    			}
    
    
    
    		}
    		catch(Exception e){
                                e.printStackTrace();
                            }
    	}
    }

  5. #5
    Tolls is offline Moderator
    Join Date
    Apr 2009
    Posts
    11,755
    Rep Power
    19

    Default

    Right, now we can actually see what's going on.
    You close the connection (as Norm summised)...but you never reopen it, so it only works on the first time round the loop.

    By not closing it you now see that you are not getting anything from the socket. So if the readLine() returns null presumably you don't want to do the query...so put a check in there somewhere.

    Finally ensure you close your resources in a finally block.

  6. #6
    cotarelo is offline Member
    Join Date
    Mar 2010
    Posts
    43
    Rep Power
    0

    Default

    Where to put the check? What to check? I dont understand exactly but it makes sense that it works correctly the first loop because after receiving the text from the socket I receive a null, like I am sending a \r\n... which I am not.

    Here is the code that is sent to the program I pasted above. Maybe this is the problem?

    Java Code:
    private void send1ActionPerformed(java.awt.event.ActionEvent evt) {                                      
            Socket echoSocket = null;
            PrintWriter out = null;
            String userInput=("Situation1");
    
            try {
                echoSocket = new Socket("127.0.0.1", 6688);
                out = new PrintWriter(echoSocket.getOutputStream(), true);
                out.println(userInput);
                //out.close();
                //echoSocket.close();
    
    
                } catch (UnknownHostException e) {
                System.err.println("Don't know about host: 127.0.0.1 ");
                System.exit(1);
            } catch (IOException e) {
                System.err.println("Couldn't get I/O for the connection to: 127.0.0.1 ");
                System.exit(1);
            }
        }
    Last edited by cotarelo; 06-22-2010 at 10:43 AM.

  7. #7
    Tolls is offline Moderator
    Join Date
    Apr 2009
    Posts
    11,755
    Rep Power
    19

    Default

    The sedning code isn't the problem, presuming you get something from it anyway.

    It's this line:
    Java Code:
    entrada.readLine();
    And it's not a problem. It's doing what the API says it does. That is, readLine() is actually simply attemptToReadLine(). It returns null if there is nothing there to read, which most of the time there won't be.

    So you only want to do something with "str" if "str" is not null...that's your check.

  8. #8
    cotarelo is offline Member
    Join Date
    Mar 2010
    Posts
    43
    Rep Power
    0

    Default

    GREAT! It was this! I would never think like this! I was trying to fix the sender, or reopen the connection... I have so much to learn... THANK YOU A LOT!

    Not about databases anyway so maybe move to networking :P

Similar Threads

  1. Help needed with querying collections
    By Jawaharlal in forum Advanced Java
    Replies: 5
    Last Post: 04-28-2010, 04:43 PM
  2. pls..transfer data in socket
    By langkhach_codon in forum Networking
    Replies: 7
    Last Post: 03-28-2010, 05:21 AM
  3. Byte Array sending and receiving using Socket
    By venkateshcoolmoon in forum Networking
    Replies: 3
    Last Post: 01-23-2010, 07:34 PM
  4. Receiving Text over a Socket (ReadLine() problem)
    By HermanHope in forum New To Java
    Replies: 1
    Last Post: 04-09-2009, 10:35 PM
  5. querying russian data from db problem
    By mr_empty in forum JDBC
    Replies: 0
    Last Post: 03-04-2008, 07:56 AM

Tags for this Thread

Posting Permissions

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