Solved

closing a socket

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

Do You Know the 4 Main Threat Actor Types?

Do you know the main threat actor types? Most attackers fall into one of four categories, each with their own favored tactics, techniques, and procedures.

Join & Write a Comment

Suggested Solutions

For customizing the look of your lightweight component and making it look opaque like it was made of plastic.  This tip assumes your component to be of rectangular shape and completely opaque.   (CODE)
Introduction This article is the second of three articles that explain why and how the Experts Exchange QA Team does test automation for our web site. This article covers the basic installation and configuration of the test automation tools used by…
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 explains how to use the VisualVM tool for the Java platform application. This video goes into detail on the Threads, Sampler, and Profiler tabs.

746 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

Need Help in Real-Time?

Connect with top rated Experts

13 Experts available now in Live!

Get 1:1 Help Now