Solved

closing a socket

Posted on 1998-05-28
3
242 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
  • 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

Independent Software Vendors: We Want Your Opinion

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

Question has a verified solution.

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

Suggested Solutions

Title # Comments Views Activity
expectj telnet failing 5 49
check java version using powershell 13 279
Is there a simpler dropbox system? 10 44
ejb message driven bean mdb creation steps 2 34
Java had always been an easily readable and understandable language.  Some relatively recent changes in the language seem to be changing this pretty fast, and anyone that had not seen any Java code for the last 5 years will possibly have issues unde…
This was posted to the Netbeans forum a Feb, 2010 and I also sent it to Verisign. Who didn't help much in my struggles to get my application signed. ------------------------- Start The idea here is to target your cell phones with the correct…
Video by: Michael
Viewers learn about how to reduce the potential repetitiveness of coding in main by developing methods to perform specific tasks for their program. Additionally, objects are introduced for the purpose of learning how to call methods in Java. Define …
This tutorial covers a step-by-step guide to install VisualVM launcher in eclipse.

679 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