I can't seem to find a function to check to see if a connection was success

Hello everyone. I'm running into 2 problems that I can't seem to find functions for after reading the java API on socket and serverSocket.

If a client closed a connection on my server, like if someone telnets into my server, then closes the console, i get the following:

Event from: localhost->null

Exception in thread"Thread-1" java.lang.NullPointerException

at server.MultiThreadServer.run(MultiThreadServer.java:62)

at java.lang.Thread.run(Thread.java:803)

This is the check i do to avoid getting this, but it doesn't seem to work:

//close a connection on this condition.

if(csocket.getRemoteSocketAddress() ==null || input.equals("bye"))

{

System.out.println("Connection closed by client.");

break;

}

If I attempt to run a server socket on a socket that is already being used, I'd like to print out a statement saying its being used and do something about it, like let the user enter another port number. Right now I have:

publicclass MainTest{

publicstaticvoid main(String args[])throws Exception

{

//get console input

BufferedReader stdin =new BufferedReader(new InputStreamReader(System.in));

System.out.println("Enter port to run server on: ");

String input = stdin.readLine();

int servPort = Integer.parseInt(input);

try

{

ServerSocket ssock =new ServerSocket(servPort);

System.out.println("Listening on : " + ssock);

while (true){

//waiting for client to connect to server socket

Socket sock = ssock.accept();

System.out.println(sock +" connected.");

//get host information

InetAddress clientIa = sock.getInetAddress( );

String clientName = clientIa.getHostName();

String clientIp = clientIa.getHostAddress();

int localPort = sock.getLocalPort();

System.out.println("hostname: "+clientName +

'\n' +"Ip address: " + clientIp

+":"+ localPort +"\n\n");

new Thread(new MultiThreadServer(sock)).start();

}

}

catch(IOException e)

{

e.printStackTrace();

}

}

}

Me catching the IOException is too broad....if anything goes wrong it will spit out the error and stop program execution as it should.

I tried

if(ssock.isClosed()){ System.out.println("Socket is being used, try another");

but it doesn't work.

Also inside my server program I'm connecting to another server and if that other server isn't running I'd like to print out an error message stating that.

Right now it will just say: Connection Refused if its not running.

here's that code:

publicclass MultiThreadServerimplements Runnable{

Socket csocket;

MultiThreadServer(Socket csocket){

this.csocket = csocket;

}

publicvoid run(){

try{

//setting up channel to recieve events from the omnibus server

BufferedReader in=new BufferedReader(

new InputStreamReader(

csocket.getInputStream()));

//This socket will be used to communicate with the reciever

//we will need a new socket each time because this is a multi-threaded

//server thus, the (outputServ) will need to be

//multi threaded to handle all the output.

Socket outputServ =new Socket("localhost",1234);

if(outputServ.getLocalSocketAddress() ==null)

System.out.println("OutputServer isn't running...");

//Setting up channel to send data to outputserv

PrintWriter out

=new PrintWriter(

new OutputStreamWriter(

outputServ.getOutputStream()));

while(true)

{

//accepting events from omnibus server and storing them

//in a string for later processing.

String input = in.readLine();

//accepting and printing out events from omnibus server

//also printing out connected client information

System.out.println("Event from: " + csocket.getInetAddress().getHostName()

+"-> "+ input +"\n");

out.println(input);

out.flush();

//close a connection on this condition.

if(csocket.getRemoteSocketAddress() ==null || input.equals("bye"))

{

System.out.println("Connection closed by client.");

break;

}

}

//cleaning up

in.close();

out.close();

outputServ.close();

csocket.close();

}catch (IOException e){

System.out.println(e);

e.printStackTrace();

}

}

}

Both those conditions don't seem to work, if a client closes a connection it doesn't respond and if the server isn't running on port 1234, i get that connection refused.

Any help would be great!

[7802 byte] By [lokiea] at [2007-11-27 9:54:30]
# 1
I don't understand what you're asking for the first part.For the second part, what else would you expect? If there's no server listening on a given port, you won't be able to open a connection to that port.
jverda at 2007-7-13 0:24:25 > top of Java-index,Core,Core APIs...
# 2

Thanks for the responce jverd,

Well for the first part, when I have my server up, a client connects to it. They send me some data via Telnet or some other client. But what if it the client closes the connection? I was trying to find a way to check for this.

because here's my loop that is accepting incoming strings on my server:

while(true)

{

//accepting events from omnibus server and storing them

//in a string for later processing.

String input = in.readLine();

//accepting and printing out events from omnibus server

//also printing out connected client information

System.out.println("Event from: " + csocket.getInetAddress().getHostName()

+"-> "+ input +"\n");

out.flush();

out.println(input);

out.flush();

[b]//closes a connection on this condition.

if(csocket.getRemoteSocketAddress() == null || input.equals("bye"))

{

System.out.println("Connection closed by client.");

break;

}[/b]

}

//cleaning up

in.close();

out.close();

outputServ.close();

csocket.close();

If the string it accepts is "bye" the program will close the connection correctly.

But if the user just closes down the console on telnet, i'll get that exception thrown error.

Exception in thread "Thread-1" java.lang.NullPointerException

at server.MultiThreadServer.run(MultiThreadServer.java:62)

at java.lang.Thread.run(Thread.java:803)

So i'm trying to figure out a way if the client's connection is suddenly lost, I'd like to break out of the loop and print out a message saying: "Client closed connection or client connection lost."

For the second part, what else would you expect? If there's no server listening on a given port, you won't be able to open a connection to that port.

Correct, I was just asking is there a way to check for this condition? so if there is no server listening on that port given, I can print out a message saying, "No connection is found on that server". So the user knows why he/she is getting that error and can start the other server on that port.

Thanks

Message was edited by:

lokie

Message was edited by:

lokie

lokiea at 2007-7-13 0:24:25 > top of Java-index,Core,Core APIs...
# 3
First part....keep reading the channel until you get -1when you get -1 from the read method, it means that the connection is brokenSecond part...I don't understand....reading too see if I can help
pbulgarellia at 2007-7-13 0:24:26 > top of Java-index,Core,Core APIs...
# 4
If i got what you mean....the second part is easily solved using try catchput your new Socket() on a try statement, and if a Exception is trowed you will know that the connection can't be established and show your messages...hope I helped
pbulgarellia at 2007-7-13 0:24:26 > top of Java-index,Core,Core APIs...
# 5

> Well for the first part, when I have my server up, a

> client connects to it. They send me some data via

> Telnet or some other client. But what if it the

> client closes the connection? I was trying to find a

> way to check for this.

> But if the user just closes down the console on

> telnet, i'll get that exception thrown error.

If you read the docs for getRemoteSocketAddress, you'll see that it returns null if the socket is not connected yet. It doesn't seem like it goes to null when the socket closes.

I believe if you're blocked on a read call when the socket closes, you'll get InterruptedException, and if it closes when you're not blocked but you try to read after it's closed, you'll get IOException. Dig into the docs, play around and see what happens.

I don't think you can know that the remote has shut down until you try to read, or maybe test isConnected

> For the second part, what else would you expect?

> If there's no server listening on a given port, you

> won't be able to open a connection to that port.

>

>

> Correct, I was just asking is there a way to check

> for this condition? so if there is no server

> listening on that port given, I can print out a

> message saying, "No connection is found on that

> server". So the user knows why he/she is getting

> that error and can start the other server on that

> port.

I still don't understand. You try to connect, the connection fails. You can print out whatever message you want.

jverda at 2007-7-13 0:24:26 > top of Java-index,Core,Core APIs...
# 6

> First part....

> keep reading the channel until you get -1

> when you get -1 from the read method, it means that

> the connection is broken

>

Ah, right. -1 is end of stream, so if the remote end sends everything and closes cleanly, you'll read -1.

However, I think there are cases where you may get a SocketException, so you should probably catch that too.

jverda at 2007-7-13 0:24:26 > top of Java-index,Core,Core APIs...
# 7

Thanks for the help guys!

adding -1 to the stream worked perfect:

i have it like this:

String input;

//accepting events from omnibus server and storing them

//in a string for later processing.

while ((input = in.readLine()) != null)

{

//accepting and printing out events from omnibus server

//also printing out connected client information

System.out.println("Event from: " + csocket.getInetAddress().getHostName()

+"-> "+ input +"\n");

out.flush();

out.println(input);

out.flush();

//close a connection on this condition.

if(in.read() == -1)

{

System.out.println("Connection closed by client.");

break;

}

}

//cleaning up

in.close();

out.close();

outputServ.close();

csocket.close();

}

I had one last question, when I catch a socketExpection, such as, if the user enters a port that is already in use, I would like to give them the chance to enter another port before stopping the program.

I'm not sure how I can do this with exceptions though, like i have:

//setting up sockets

ServerSocket ssock = null;

Socket sock = null;

try

{

//setting up server to run on servPort

ssock = new ServerSocket(servPort);

...

...

...

catch (SocketException e )

{

System.out.println ("Socket error: " + e);

}

now inside that catch block, is there a way for me to allow the user to enter another socket and try again? or am I approaching this wrong?

while(true)

{

if the port is already been used

allow the user to enter in another port number

else

break;

}

I'm confused on how this will work though becuase:

once it hits this line:

ssock = new ServerSocket(servPort);

the exception is thrown and it jumps down to the catch block,

now inside that catch block how would I let the user enter in another port number and try this line of code again?

ssock = new ServerSocket(servPort); //this time with the new servPort number?

Thanks!

lokiea at 2007-7-13 0:24:26 > top of Java-index,Core,Core APIs...