views:

260

answers:

4

i hava a program connect to server through xot (x25 over tcp/ip) protocol.

i have a thread to connect, send recv data with server using xot library.

public class MyThread extends Thread{

    public MyThread() {
    }

    @Override
    public void run(){
        // init sock
        ...

        // connect to server
        sock.connect("server_address", timeout);

        System.out.println("send data ..");
        sock.send(data);

        System.out.println("send data ok, recv data ..");

        Data data = sock.recv();
        System.out.println("recv data ok");
    }

}

My lib i use can handle connect timeout, but there is no method like setSoTimeout() to handle timeout when send & recv data.

So, i dont know how to stop mythread right-way when send & recv method run for a long time.

anyone could suggest me some solution.

thanks

Quan

+1  A: 
MyThread myt = new MyThread();
myt.start();
... later on ...
myt.interrupt();

Note that interrupt() isn't completely fool-proof (read the docs), but the odds are good that it will help in your situation. You may additionally need to modify your own code (within MyThread) to check the interrupted status using interrupted or isInterrupted

Jon Bright
Note that you need a second Thread (or Timer) to fire the interrupt as the thread cannot interrupt itself.
Thilo
ok, thanks all :)
QuanNH
oh, how to add code to check interrupt status when mythread suspend at recv method to wait resp from server (no print "recv data ok")
QuanNH
I don't think interrupt() works for his custom socket library, unless it is implemented by nio. If not, recv already blocks and there's no ways of periodically checking interrupt status.
bryantsai
+1  A: 

I didn't catch whether the send/receive you're blocking/waiting on is a "normal" TCP/IP socket; but if so, it's fairly easy to abort an I/O operation from the outside by simply closing the socket. This is not widely known but is AFAIK perfectly legal, and it works like a charm.

The I/O operation yields an IOException, of course, but that's easy enough to catch and then you can exit your Thread's run() method.

Carl Smotricz
i will try, thank you
QuanNH
A: 

You will need to use a volatile flag and a while loop that counts down until the timeout is exhausted or a connection happens.

mP
how to add a while loop while my thread suspend at recv method to wait data from server ?
QuanNH
A: 

Hello Quan! I see that you have used a xot library for Java. i`m looking for one but i haven't found anything yet. Could you give me a little help please?

Did you have to create the x25 data and xot header by hand and then send it using Java TCP implementation?

Well, that 's all ... Thanks in advance!

Leandro Aispuru