Solved

closing a socket

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

Free Tool: IP Lookup

Get more info about an IP address or domain name, such as organization, abuse contacts and geolocation.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

Question has a verified solution.

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

Suggested Solutions

Title # Comments Views Activity
Should localization be done inside spring controller 5 32
couple of eclipse 5 45
tomcat administrtor 12 58
servlet web applications   metadata-complete="true" or false 3 104
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…
Java functions are among the best things for programmers to work with as Java sites can be very easy to read and prepare. Java especially simplifies many processes in the coding industry as it helps integrate many forms of technology and different d…
Viewers learn how to read error messages and identify possible mistakes that could cause hours of frustration. Coding is as much about debugging your code as it is about writing it. Define Error Message: Line Numbers: Type of Error: Break Down…
This tutorial covers a step-by-step guide to install VisualVM launcher in eclipse.

791 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