Socket Server problem

Hey all,

I'm working on a Socket Server that connects to a database, and then allows clients to connect to itself and process Database queries through the socket server. Currently my socket server works for the first client, but when I try to connect and run a query the second time I get the following error.

java.lang.NullPointerException

at SocketServerThread.sendStmt(SocketServerThread.java:84)

at SocketServerThread.run(SocketServerThread.java:37)

I assume this is probably having something to do with me not closing connections correctly.

Any advice would be greatly appreciated.

Thank you for your time.

Here is the server code:

import java.net.*;

import java.io.*;

import javax.naming.*;

import javax.sql.DataSource;

import java.sql.Connection;

import java.sql.PreparedStatement;

import java.sql.ResultSet;

import java.sql.SQLException;

import java.util.Hashtable;

/*

*

*/

publicclass SocketServer{

staticboolean listening =true;

publicfinalstatic String JNDI_FACTORY="weblogic.jndi.WLInitialContextFactory";

publicvoid endListening()

{

listening =false;

}

privatestaticvoid usage()

{

System.err.println("Usage: SocketServer " +"<hostname> <port number>");

System.exit(-1);

}

publicstaticvoid main(String[] argv)throws IOException

{

ServerSocket serverSocket =null;

// Get hostname and port from arguments

if (argv.length < 2)

{

usage();

}

String host = argv[0];

int port = 0;

InitialContext ic =null;

DataSource ds =null;

Connection conn =null;

try

{

port = Integer.parseInt(argv[1]);

}

catch (NumberFormatException nfe)

{

usage();

}

// Set up Socket Server on Port

try{

serverSocket =new ServerSocket(4444);

}catch (IOException e){

System.err.println("Could not listen on port: 4444.");

System.exit(-1);

}

//Set up connection to DB

try

{

ic = getInitialContext("t3://" + host +":" + port);

ds = (DataSource) ic.lookup("jdbc-database");

if ( ds !=null )

{

conn = ds.getConnection();

if (conn !=null )

System.out.println("Got a connection from datasource at " + host +" at port " + port );

else

{

thrownew Throwable("Connection is null");

}

}

else

System.out.println("DataSource is null");

}

catch (Throwable t)

{

t.printStackTrace();

System.exit(-1);

}

// Wait for connection from client, then create new thread to handle client

while(listening)

{

new SocketServerThread(serverSocket.accept(), conn).start();

}

serverSocket.close();

}

privatestatic InitialContext getInitialContext(String url)

throws NamingException

{

Hashtable env =new Hashtable();

env.put(Context.INITIAL_CONTEXT_FACTORY, JNDI_FACTORY);

env.put(Context.PROVIDER_URL, url);

returnnew InitialContext(env);

}

}

Here is the SocketServerThread code:

import java.net.*;

import java.io.*;

import java.sql.Connection;

import java.sql.PreparedStatement;

import java.sql.ResultSet;

import java.sql.SQLException;

/*

*

*/

publicclass SocketServerThreadextends Thread{

privatestatic Socket socket =null;

privatestatic Connection conn=null;

privatestatic PrintWriter out =null;

public SocketServerThread(Socket theSocket, Connection theConn){

super("SocketServerThread");

socket = theSocket;

conn = theConn;

}

publicvoid run(){

PreparedStatement stmt =null;

try

{

out =new PrintWriter(socket.getOutputStream(),true);

stmt = conn.prepareStatement("SELECT USER_NAME FROM LOGIN_INFO");

sendStmt(stmt);

}

catch( SQLException sqe)

{

sqe.printStackTrace();

}

catch(IOException e){e.printStackTrace();

}

//Send done response and close Connections

try

{

out.println("done");//Lets client know that it is done

socket.close();

conn.close();

out.close();

}catch(IOException e){e.printStackTrace();}

catch(SQLException e){e.printStackTrace();}

}

// Execute prepared statement and send back the results

publicvoid sendStmt(PreparedStatement statement)

{

try

{

ResultSet rs = statement.executeQuery();

while ( rs.next() )

{

out.println(rs.getString(1));

}

out.close();

}

catch( SQLException sqe)

{

sqe.printStackTrace();

}

finally

{

try

{

statement.close();

}catch(SQLException e){e.printStackTrace();}

}

}

}

[10412 byte] By [Newworld20a] at [2007-11-27 11:35:12]
# 1

ok, I found the problem as to the null pointer exception.

I close the connection in my socketserverthread class which makes the connection null. When my server calls a new thread on the second connection it is passing a null for the connection. Removing the conn.close() in my thread fixes the problem.

My other problem is since my server will *ideally* run forever, I need to make sure all connections are closed and only the server's socket connection stays open after a client is finished.

Currently, (By using a port watching program) when the server starts up it has one port in use. When a client connects there are 4 new connections used for a total of 5. When the client has finished and "leaves", it currently closes two of the 5 connections leaving a total of 3 left. 2 connections hanging, and the servers connection. One of the two hanging connections has a "Timed_Wait" status which eventually gets cleaned up after a few min, but the other has an "Established" status and stays there. This is obviously bad for my server as after each new client connects it leaves one open connection when it is done.

Newworld20a at 2007-7-29 17:01:30 > top of Java-index,Java Essentials,Java Programming...
# 2

This leak is in your code. Make sure your accepted sockets get closed via every execution path, regardless of whether you read EOF or got an IOException from each of them. Possibly the ESTABLISHED connection is to the database? Make sure you release DB statements and connections via all possible execution paths too.

ejpa at 2007-7-29 17:01:30 > top of Java-index,Java Essentials,Java Programming...