Solved

closing a socket

Posted on 1998-05-28
3
249 Views
Last Modified: 2010-03-30
I have a very basic question: how can I test a Socket to determine whether or not it is open?

I know I receive an exception if the socket is unexpectedly closed.  I also know I receive a known return code (e.g. null) if I read or write to a closed socket.  But how do I ask a Socket whether or not it is open without having to read or write?

Thanks!

Joe 
0
Comment
Question by:BrindleFly
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 2
3 Comments
 
LVL 4

Expert Comment

by:evijay
ID: 1221647
I didnt find any way to do this (as per my knowledge). The best way to handle this is

After you say
InputStream is = socket.getInputStream();
create a push back input stream
PushbackInputStream ps = new PushBackInputStream (ps);

use ps instead of is to read data from socket.

Write an utility routine to test for socket closure as below

public static boolean isSocketClosed(PushbackInputStream pInpStr) throws Exception
{
        int rd;
        try { rd  = pInpStr.read(); } catch (Exception e) { System.out.println("Socket closed !!"); return true; }
        System.out.println("not yet closed!!");
        pInpStr.unread(rd);
        return false;
}

0
 

Expert Comment

by:Charmaine041198
ID: 1221648
Do you mean to test if a socket is still valid?

eg.
// start

Socket mysocket = new Socket(hostname,portnum);

// Test if socket is valid
if(mysocket = null) {
    // socket closed, do something
} else {
    // socket open, read or write using socket
}

// end
0
 
LVL 4

Accepted Solution

by:
evijay earned 100 total points
ID: 1221649
What i said was, once you open a socket, anyway, you will get the socket input and output streams.
Instead of using Socket input stream, i want you to pass it thru pushback input stream and then use it.
Here is an example of the code which can answer your doubts.

//server code file - tserv.java
import java.io.*;
import java.net.*;
public class tserv {

      public static void main(String args[]) throws Exception
      {
            byte b[] = new byte[1000];
            ServerSocket s = new ServerSocket(13500);
            Socket ss = s.accept();
            OutputStream os = (OutputStream) ss.getOutputStream();
            for (int i = 0; i < 100; i++) {
                  os.write(b);
                  System.out.println("written ");
                  Thread.currentThread().sleep(5000);
                  // suppose some serious error occured
                  System.exit(1);
            }
      }
}


// client code file - tcli.java

import java.io.*;
import java.net.*;
public class tcli {
public static boolean isSocketClosed(PushbackInputStream pInpStr) throws Exception
{
      int rd;
      try { rd  = pInpStr.read(); } catch (Exception e) { System.out.println("Socket closed !!"); return true; }
      System.out.println("not yet closed!!");
      pInpStr.unread(rd);
      return false;
}
public static void main(String [] args) throws Exception
{
      Socket s  = new Socket("napa.mcom.com", 13500);
      PushbackInputStream pInpStr;
      pInpStr = new PushbackInputStream(s.getInputStream());
      byte b[] = new byte[1000];
      while (true) {
        
            Thread.currentThread().sleep(100);
            if (isSocketClosed(pInpStr) == false)
                  pInpStr.read(b);
            else
                  break;
            System.out.println("Read");
            Thread.currentThread().sleep(3000);
      }
      
}
}


0

Featured Post

MS Dynamics Made Instantly Simpler

Make Your Microsoft Dynamics Investment Count  & Drastically Decrease Training Time by Providing Intuitive Step-By-Step WalkThru Tutorials.

Question has a verified solution.

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

An old method to applying the Singleton pattern in your Java code is to check if a static instance, defined in the same class that needs to be instantiated once and only once, is null and then create a new instance; otherwise, the pre-existing insta…
Java contains several comparison operators (e.g., <, <=, >, >=, ==, !=) that allow you to compare primitive values. However, these operators cannot be used to compare the contents of objects. Interface Comparable is used to allow objects of a cl…
Viewers learn about the third conditional statement “else if” and use it in an example program. Then additional information about conditional statements is provided, covering the topic thoroughly. Viewers learn about the third conditional statement …
Viewers will learn about if statements in Java and their use The if statement: The condition required to create an if statement: Variations of if statements: An example using if statements:

739 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