Want to win a PS4? Go Premium and enter to win our High-Tech Treats giveaway. Enter to Win

x
?
Solved

I would like to know if the socket is alive?

Posted on 2002-03-03
12
Medium Priority
?
408 Views
Last Modified: 2010-03-31
I would like to know if the socket is alive "without" Blocking IO.
I know the way with the InputStream.read() method but this method making blocking IO and i wouldn't want this because i would like to read the InputStream for the other methods.

Thanks Nikos Tzelvenzis.
0
Comment
Question by:tzelve
[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
  • 4
  • 3
  • 3
  • +1
12 Comments
 
LVL 5

Expert Comment

by:LexZEUS
ID: 6838203
You can use available() before trying to read() it ..

if (inpustream.available()>0)
   {
   // do whatever or read from the stream ...
   }

should work just fine :)
0
 
LVL 5

Expert Comment

by:LexZEUS
ID: 6838435
Above method cannot detect whether the remote socket is down or not...

This is a plain trick to detect remote socket is down or not:

public void connect() {
try
{
  Socket sock = new Socket(......);
  sock.setSoTimeout(5000);
  InputStream in = sock.getInputStream();
}
catch (Exception ex)
{
  System.out.println("Cannot connect to remote host: "+ex.toString());
  return;
}

while(true)
{
byte bt;
try {
    bt = in.read();
    }
catch (java.io.InterruptedIOException ex1)
    {
    System.out.println("remote host never send anything for 5 seconds!");
    // Thread.currentThread().sleep(100) to rest for a moment?
    continue; // try to listen again ...
    }
catch (java.io.IOException ex2)
    {
    System.out.println("remote host is down!!!");
    break; // to exit from loop,
           // and maybe.. reconnect again later?
    }
System.out.println("Receive data: "+bt);
}
} // end of method connect()


rgds,

Alex
0
 
LVL 9

Expert Comment

by:Venci75
ID: 6838554
try this:
InputStream in = socket.getInputStream();
BufferedInputStream bis = new BufferedInputStream(in);
bis.mark(1);
int r = bis.read();
bis.reset();
...
0
Concerto Cloud for Software Providers & ISVs

Can Concerto Cloud Services help you focus on evolving your application offerings, while delivering the best cloud experience to your customers? From DevOps to revenue models and customer support, the answer is yes!

Learn how Concerto can help you.

 

Author Comment

by:tzelve
ID: 6838594
Thanks i know these way but the problem is that.
The class run as thread and the run() method waitting to come data all the time.
I have some methods like GetTime() (example) which send and receive data via the Socket...the problem generate when i would like to receive data from GetTime() method because the run() method receive first the data.It's work perfect with availiable() method of InputStream Class but i can't detect when the socket dies...
I think to make with the PushbackInputStream class which have unread method() but i am thinking about this.

If you have something beter tell me.

Thanks.
0
 

Author Comment

by:tzelve
ID: 6838604
Thanks i know these way but the problem is that.
The class run as thread and the run() method waitting to come data all the time.
I have some methods like GetTime() (example) which send and receive data via the Socket...the problem generate when i would like to receive data from GetTime() method because the run() method receive first the data.It's work perfect with availiable() method of InputStream Class but i can't detect when the socket dies...
I think to make with the PushbackInputStream class which have unread method() but i am thinking about this.

If you have something beter tell me.

Thanks.
0
 
LVL 5

Expert Comment

by:LexZEUS
ID: 6838647
Ok, set the timeout to 10 when you instantiate the socket:

Socket sock = new Socket("myserver", 7777);
sock.setSoTimeout(10);

10 means 10 mili-secs, it will trigger InterruptedIOException if read() cannot retrieve any data in 10 mili-secs. So if you catch this exception, just ignore it. But if the exception is IOException, that means read() cannot retrieve data because remote server is down.

This is in your thread's run():

public void run()
{
byte timeBuffer[] = new byte[6];  
while(true)
  {
  // try to sleep for 1 seconds, so the output will be
  // the same as clock's tick
  try { sleep(1000); } catch (Exception ex) {}

  // if 1 sec already expired, now get current time
  // from server
  try { in.read(timeBuffer); } // read time from socket

  // if server never response but server is not
  // dead, then loop from beginning again
  catch (InterruptedIOException ex1) { continue; }

  // if server never response because server is dead,
  // then quit from program ...
  catch (IOException ex2) {
        System.out.println("Server is down");
        break; // to exit from loop,
        }

  // this will print current time:
  System.out.print(timeBuffer[0]+"-");
  System.out.print(timeBuffer[1]+"-");
  System.out.print(timeBuffer[2]+", ");
  System.out.print(timeBuffer[3]+":");
  System.out.print(timeBuffer[4]+":");
  System.out.print(timeBuffer[5]+"");
  }
}

Assuming if the server push byte[] like this:
byte[] bt = { 16, 1, 78, 12, 0, 0 };
this means 16 JAN 1978, at 12:00:00

Then, the client should be able to print in the loop:
16-1-78, 12:0:0

I think this code will this work fine.. :)
0
 

Author Comment

by:tzelve
ID: 6840143
Good way LexZEUS nut it isn't for this application.
I have the run() method which read the InputStream of the Socket and i would have another methos ex. called GetTime() which send and receive some data.If The read() in Run() method waitting (with or without timeout) will catch first the data and the other method will lose the data that assign for this.
I will try PushbackInputStream Class maybe unread() method of this Class will do that i want.
0
 
LVL 9

Expert Comment

by:Venci75
ID: 6844266
Hi tzelve,
I will repeat my suggestion:
wrap you socket input stream with a BufferedInputStream
InputStream in = socket.getInputStream();
BufferedInputStream bis = new BufferedInputStream(in);

The mark your position:
bis.mark(1);

and try to read - only to check whteher everything is OK:
int r = bis.read();

reset the the readed data:
bis.reset();

this is the unread() method that you want.
This way you wan't lose any data!
0
 

Author Comment

by:tzelve
ID: 6854265
Thanks Venci75 but doesn't work. My code is :



public class ClientSocket extends Thread {
   
.....


    public String GetServerTime() {
        String Answer = null;
        if (Connected) {
            SocketIsBuzy = true;                                            //Mark The Socket as buzy
            try {
                out.write(2);                                               //Send the Command Number
                out.flush();                                                //Start to send Data From Socket's Bufffer To Socket
                Answer = ReadString();                                      //Read The Received Data
            }
            catch (IOException e) {
                FireSocketError(DisconnectError);                           //Error to trasmit data (or Receive)
            }
            SocketIsBuzy = false;                                           //Unmark The Socket as buzy
        }
        return Answer;                                                      //Returned Data
    }




   public void run() {
        int CommandNumber = 0;                                              //Temporary Variable to Stora The Command Number That Received
        if (Connected == false)                                             //Send No Connected Error
            FireSocketError(NoConnectError);                                //Error to trasmit data (or Receive)
        PushbackInputStream test = new PushbackInputStream(in);
        while (Connected) {                                                 //Never Stop The Procedure until Deisconnect Socket
           TimerTask PingTask = new TimerTask() {            
            public void run() {
                 Ping();}
           };
           PingTimer.schedule(PingTask,0,1000);
            try {
                while ((in.available() == 0 ) || (SocketIsBuzy == true)){   //Wait If The Socket Is Buzy
                    sleep(100);
                }
               
                SocketIsBuzy = true;                                        //Flaged the socket as buzy
                CommandNumber = in.read();
                if (CommandNumber == 10) {                                  //If The Command Is Ping
                    out.write(10);                                          //Answer The Same
                    out.flush();                                            //Start to send Data From Socket's Bufffer To Socket
                }
                else if (CommandNumber == 11) {                             //If The Command Is GetUserName
                    SendString("petros");                                   //Answer For Test
                    out.flush();                                            //Start to send Data From Socket's Bufffer To Socket
                }
                else if (CommandNumber == 12) {                             //If The Command Is GetUserAccess
                    out.write(10);                                          //Answer For Test
                    out.flush();                                            //Start to send Data From Socket's Bufffer To Socket
                }
                else if (CommandNumber == 13) {                             //If The Command Is GetUserFullName
                    SendString("Pelopidas ntrompogianos");                  //Answer For Test
                    out.flush();                                            //Start to send Data From Socket's Bufffer To Socket
                }
                SocketIsBuzy = false;                                       //flaged the socket as not buzy
            }
            catch (IOException e){
                System.out.println("Kopike!!!");
                FireSocketDisconnect();                                     //Error to trasmit data (or Receive)
            }
            catch (InterruptedException e) {
                FireSocketError(SleepThreadError);                          //Error to trasmit data (or Receive)
            }
        }
    }
}


When i call GetServerTime the run method catch first the data if i do this with the mark.
0
 
LVL 9

Accepted Solution

by:
Venci75 earned 200 total points
ID: 6855720
then try this:
public String GetServerTime() {
synchronized (socket) {
...
} // end synchronyzed
}

void run() {
...
while (Connected){
synchronized (socket) {
...
}
}
Now you can be sure that when the GetServerTime starts, the socket will processed only by this method
0
 
LVL 35

Expert Comment

by:girionis
ID: 8658271
No comment has been added lately, so it's time to clean up this TA.

I will leave a recommendation in the Cleanup topic area that this question is:

- points to Venci75

Please leave any comments here within the
next seven days.

PLEASE DO NOT ACCEPT THIS COMMENT AS AN ANSWER !

girionis
Cleanup Volunteer
0

Featured Post

Free Tool: Path Explorer

An intuitive utility to help find the CSS path to UI elements on a webpage. These paths are used frequently in a variety of front-end development and QA automation tasks.

One of a set of tools we're offering 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

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…
Are you developing a Java application and want to create Excel Spreadsheets? You have come to the right place, this article will describe how you can create Excel Spreadsheets from a Java Application. For the purposes of this article, I will be u…
Viewers learn about the scanner class in this video and are introduced to receiving user input for their programs. Additionally, objects, conditional statements, and loops are used to help reinforce the concepts. Introduce Scanner class: Importing…
Viewers will learn about the regular for loop in Java and how to use it. Definition: Break the for loop down into 3 parts: Syntax when using for loops: Example using a for loop:
Suggested Courses

636 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