How to use threads to reconnect a socket to a server in TCP/IP

I want to know how to reconnect a socket to a server in TCP.
Actually i wanted to do reconnection whenever a SocketException for broken connection etc. is thrown in my code. This I want to do for a prespecified number of times for reconnection in case of broken connection.When this number decrements to zero the program will exit printing some error message. I was planning to use threads by way of having some Exception Listeners but i am not sure How?
Any suggestions will be really helpful..
please help.
Edited by: danish.ahmed.lnmiit on Jan 28, 2008 2:44 AM

I want to know how to reconnect a socket to a server in TCP.There is no reconnect operation in TCP. You have to create a new Socket.

Similar Messages

  • How to use threads in JSP???

    hello
    i want to use threads with JSP.
    i want to write a jsp page which will
    start 2 different threads. the 1st thread should just display a message and the second page should redirect this page to another jsp page.
    till the redirection is goin on, the message should be displayed in the browser from the 1st thread.
    i dont know actually how to use threads in JSP by implementing the Runnable insterface, if not m then how do i do it ??
    thanx
    Kamal Jai

    Why do you want to use threads to do this ??
    If you write a message and do a redirection, the message will be displayed until the other page will be loaded into the browser...
    I already launched a thread from a JSP but it was for a four hour process where the user can close his browser windows.

  • How to finish thread, listening to a socket input?

    Hello!
    Can anybody tell me how to correctly interrupt/close thread, listening to a socket input from a server?
    I have a separate thread which listens to an input from server. When a client disconnects from server, it should be closed. I do:<p>
    <code>
    Thread th=new Thread(myRunnable);
    th.start();
    Thread old=th;
    th=null;
    old.interrupt();
    </code>
    But nevertheless I get a SocketException. This is because in thread I use<p>
    <code>
    public void run()
    MyMessage incoming=null;
    while((incoming=(MyMessage)reader.readObject())!=null)
    </code>
    and I/O methods are blocking current thread's running process. Is this technics correct? Any other suggestions?
    Thanx.

    There have been issues with achieving consistent interruption of I/O across all platforms. The recommended approach seems to be to close the socket that the other thread is using, rather than interrupting the other thread.
    If you first set a flag (declare it volatile) before closing the socket, you can use the fact that this flag is set as an indication in the other thread that the exception it gets should just be ignored.
    Sylvia.

  • How to use URL class instead of Socket

    Hi all. I am developing a small inventory control system for a warehouse.
    I am suing a Java desktop application that connects to a servlet via Internet.
    I have been searching the net how to use JSSE for my application since i am new to secure sockets and JSSE.
    Since I havent implemented security In my current system yet, i am using URLConnection conn = url.openConnection(); to connect to a servlet.
    However, in a good tutorial that I found about JSSE, sockets are used directly for connection, insted of URLCOnnection. They use the code like this: SSLSocketFactory sf = sslContext.getSocketFactory();
    SSLSocket socket = (SSLSocket)sf.createSocket( host, port ); Since, using sockets is overly complex for me, I want to make use of the URLConnection class instead to keep it simple.
    Could anyone please tell me how to make use of the URLConnection class to establish secure http connection.
    by the way, the tutorial is here:
    http://www.panix.com/~mito/articles/articles/jsse/j-jsse-ltr.pdf
    thanks.

    Here you go. The following code snippet allows you post data to http URL. If you have to do the same to https URL , please let me know.
    OutputStream writeOut = null;
    HttpURLConnection appConnection = null;
    URL appUrlOpen = null;
    //data to be posted.
    String data = "This is the test message to post";
    byte[] bytesData = this.data.getBytes();
    appUrlOpen = new URL(""Your Servlet URL");
    appConnection = (HttpURLConnection) appUrlOpen.openConnection();
    appConnection.setDoOutput(true);
    appConnection.setDoInput(true);
    appConnection.setUseCaches(false);
    appConnection.setInstanceFollowRedirects(false);
    appConnection.setRequestMethod("post");
    appConnection.setRequestProperty("Content-Type","application/text");
    appConnection.setRequestProperty("Content-length", String.valueOf(bytesData.length));
    writeOut=appConnection.getOutputStream();
    writeOut.write(bytesData);
    writeOut.flush();
    writeOut.close();
    String inputLine;
    StringBuffer sb = new StringBuffer();
    reader = new BufferedReader(new InputStreamReader(appConnection.getInputStream()));
    char chars[] = new char[1024];
    int len = 0;
    //Write chunks of characters to the StringBuffer
    while ((len = reader.read(chars, 0, chars.length)) >= 0)
    sb.append(chars, 0, len);
    System.out.println("Response " + sb.toString());
    reader.close();
    sb=null;
    chars = null;
    responseBytes = null;
    ******************************************************************************************

  • How to use thread only for progress bar.....

    Hello,
    I am working on an application which is taking time to load. Now I want to use a progress bar to tell the user of the application that It is taking time to load. How to do it... I read the Java swing tutorial and went through the example. Please tell me what to do. Because I am unfamiliar with Threads and I am not using thread anywhere in my application.

    You are using threads. All Java execution occurs on threads. Write a Java GUI and you're in a multithreaded environment - there's no way out of that.
    If your "application is a complex one" then you would be better advised to understand threads than to try and pretend that they don't exist. For a start, if you don't think you're using threads then you're destined to run in to all sorts of problems as regards an unresponsive GUI, as you're probably now finding out.

  • How to use Thread

    Hi,
    I am trying to write a program that does a background process. The process is controlled by two buttons: Start and Stop. I thought I'd use threads, but it does not work; the start button remains depressed and the user cannot click on the Stop button. The line calling run() is executed and execution transfers to the run method in my Thread subclass, which is wrapped in an infinite loop. The line after the run() method is never reached. It is as if it is not creating an extra thread at all.
    I have written something basic which is similar, the same problem occurs with this code:
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import javax.swing.JButton;
    import javax.swing.JFrame;
    import javax.swing.JPanel;
    public class CounterFrame extends JFrame {
        private JPanel pnButtons;
        private JButton btStart;
        private JButton btStop; 
        private ThreadTester threadtester;
        public CounterFrame() {
            pnButtons = new JPanel();
            btStart = new JButton("Start");
            btStop = new JButton("Stop");
            btStart.addActionListener(new StartListener());
            btStop.addActionListener(new StopListener());   
            pnButtons.add(btStart);
            pnButtons.add(btStop);
            add(pnButtons);
            pack();
            threadtester = new ThreadTester();
        private class StartListener implements ActionListener {
            public void actionPerformed(ActionEvent e) {
                threadtester.run();
        private class StopListener implements ActionListener {
            public void actionPerformed(ActionEvent e) {
                try {
                    threadtester.sleep(Long.MAX_VALUE);
                } catch (InterruptedException ex) {
                    ex.printStackTrace();
        private class ThreadTester extends Thread {
            int counter;
            public ThreadTester() {
                counter = 0;
            public void run() {
                while(true) {
                    System.out.println(counter);
                    counter++;
                    try {
                        sleep(1000);
                    } catch (InterruptedException ex) {
                        ex.printStackTrace();
                    yield();
        public static void main(String args[]) {
            java.awt.EventQueue.invokeLater(new Runnable() {
                public void run() {
                    new CounterFrame().setVisible(true);
    }Can anyone advise where I am going wrong, please?

    Please run, don't walk to the article on the Sun site (you can search for it) entitled Concurrency and Swing (or something similar). Problems I see include:
    1) Don't call run on a thread as that will just "run" the run method and not create a background thread. Instead you call "start".
    2) Don't call Thread.sleep() on the EDT or the Event Dispatch Thread. This is the single thread that Swing uses to draw components and to interact with the user. Calling Thread.sleep on it will put your whole program to sleep which is not what you want.
    3) Consider using a Swing Worker, or better still a Swing Timer.
    Again, read the article and you will understand this better.

  • How to use Threads in Java?

    Hi all,
    I want to run many programs in the same time. So i want to know if anybody can help me using threads in java. Any help or code will be very appreciated!
    Thanks in advance,
    A. Santos

    All you have to do is create classes that extend Thread, implement their run() methods and then instantiate and call their start() methods:
    public class Class1 extends Thread {
      public void run() {
        // do what you need to do
    public class Class2 extends Thread {
      public void run() {
        // do what you need to do
    public class Class3 extends Thread {
      public void run() {
        // do what you need to do
    public class Main {
      public static void main (String [] args) {
        Class1 c1 = new Class1();
        Class2 c2 = new Class2();
        Class3 c3 = new Class3();
        c1.start();
        c2.start();
        c3.start();
    }

  • MAP Toolkit - How to use this MAP tool kit for all SQL Server inventory in new work enviornment

    Hi Every one
     Just joined to new job and planning to do Inventory for whole environment so I can get list of all SQL Server installed . I downloaded MAP tool kit just now. So looking for step by step information to use this for SQL Inventory. If anyone have documentation
    or screen shot and can share would be great.
    Also like to run It will be good to run this tool anytime or should run in night time when is less activity? 
    Hoe long generally takes for medium size environment where server count is about 30 ( Dev/Staging/Prod)
    Also any scripts that will give detailed information would be great too..
    Thank you 
    Please Mark As Answer if it is helpful. \\Aim To Inspire Rather to Teach A.Shah

    Hi Logicinisde,
    According to your description, since the issue regards Microsoft Assessment and Planning Solution Accelerator. I suggestion you post the question in the Solution Accelerators forums at
    http://social.technet.microsoft.com/Forums/en-US/map/threads/ . It is appropriate and more experts will assist you.
    The Microsoft Assessment and Planning (MAP) Toolkit is an agentless inventory, assessment, and reporting tool that can securely assess IT environments for various platform migrations. You can use MAP as part of a comprehensive process for planning and migrating
    legacy database to SQL Server instances.
    There is more information about how to use MAP Tool–Microsoft Assessment and Planning toolkit, you can review the following articles.
    http://blogs.technet.com/b/meamcs/archive/2012/09/24/how-to-use-map-tool-microsoft-assessment-and-planning-toolkit.aspx
    Microsoft Assessment and Planning Toolkit - Technical FAQ:
    http://ochoco.blogspot.in/2009/02/microsoft-assessment-and-planning.html
    Regards,
    Sofiya Li
    Sofiya Li
    TechNet Community Support

  • How to use tools to monitor databae if the production server is not direct

    accessed? We access our prod server through jump server.
    On my workstation, I have plsql developer intalled, and wonder how I can use my tool to connect to the prod server?
    Is it posible?

    846422 wrote:
    No, I support internal client. I used to support external client in other company, as long as I log into vpn, and oracle client tnsnames included those sid, I should be able to log in.
    The jump server is not citrix, it is another unix server with ssh ability. I guess it is firewall issue.
    How to get around with it? change firewall rule
    >
    It seems I have to do all command line scripts from now on.yes & enjoy!

  • How to use Threads

    I have a number of objects which extend Thread, and I want to set them all running, and then 'wait' for them all to finish, before doing something else.
    The pseudocode for what I want to do is given below:
    while threads not finished {
    wait();
    Finshed!
    I was adding them all to a ThreadGroup and waiting until ThreadGroup.activeCount() == 0, but the spec of my code says I can't use the Thread constructor which takes the group as a parameter.
    Therefore, my problem is this: how to I implement the above pseudocode so I use wait()?
    Thanks!

    If you strictly have to use wait(), seems like you will need to change your thread class implementations as you need to some object, which is synchronized and shared between all the threads. I dont think its going to be a good solution for you.
    In case you want to avoid all that, using join all the threads would help, code piece for this is:
    public class ThreadsJoin {
        public static void main(String[] args) {
            MyThread[] threads = new MyThread[10];
            for (int x = 0; x < threads.length; x++) {
                try {
              threads[x] = new MyThread();
              threads[x].start();
                }catch(Exception e) {
                    e.printStackTrace();
            for (int x = 0; x < threads.length; x++) {
                try {
              threads[x].join();
              System.out.println("Thread "+ x +" finished");
                }catch(Exception e) {
                    e.printStackTrace();
            System.out.println("All threads finished... so in main");
    class MyThread extends Thread {
            public void run() {
                try {
                Thread.sleep(100);
                }catch(Exception e) {
                    e.printStackTrace();
                System.out.println("thread executed");
    }There are methods where you poll in for the active threads using isAlive() or getActiveCount(), but this is a better way to do the task. In fact join() is nothing but wait() for a thread to finish. You can even specify timeout for this waiting period.
    regds,
    CA

  • How to use thread to monitor a file

    Hi
    I have a situation where i want to monitor a file while current java process is running, for example
    The process would be like below,i have to do it using Java 1.4
    1 Start Main Java Class
    2 Start Another thread to monitor a file, from this main Java Class
    3 Return control back to main java class to do future processing
    4 When the process in this class is done, kill the monitor process.
    5 If the file is modified by external process, do some processing in the thread,
    What i did was as below, the main java class
    Thread t = new Thread(new TestOptimizationThreadWorker());
    t.run();
    // continue doing the process
    t.stop();the other thread class is as below
    public class TestOptimizationThreadWorker implements Runnable
         public void run()
              // monitor the external file here
    }But some how the control does not come back to main program after i run the thread,
    Any suggestions
    Ashish
    Edited by: kulkarni_ash on Sep 26, 2007 10:06 AM
    Edited by: kulkarni_ash on Sep 26, 2007 10:53 AM

    Hi
    Yes after changing, t.run() to t.start(), it works, but what are the issues you see,
    i have attached the whole code below
    Java Main Class
    public class TestOptimizationThread
         public TestOptimizationThread()
         public String doMessage()
              TestOptimizationThreadWorker tt =     new TestOptimizationThreadWorker();
              Thread t = new Thread(tt);
              System.out.println ("In Do message");
              try
                   System.out.println ("Before starting thread");
                   t.start();
                   System.out.println ("After starting thread");
              catch(Exception exc)
              finally
                   System.out.println ("in finally");
                   tt.changeB();
              return "";
         public static void main(String args[])
             new TestOptimizationThread().doMessage();
    }Java Thread class
    public class TestOptimizationThreadWorker implements Runnable
         private boolean b = true;
         public TestOptimizationThreadWorker()
              System.out.println ("Creating this class ");     
         public void run()
              System.out.println ("In Run Method");
              int i =0;
              while(b)
                   System.out.println ("int "+ i);     
                   i++;
         public void changeB()
              b = false;     
    }Ashish

  • How to use threads in this script???

    Hi, I�m new to java, and I my first script is a reciprocal link checker but I have a problem with the speed. I have the next class for check a html page to search for a string (the reciprocal link). The problem is that when I pass the script more than 50 pages to check, the proccess ibs very slow. I thought that the problem is stablishing the connections, because it makes only one at a time.
    I think, that with threads the I can accelerate the proccess, but I don�t know how to implement here. If you can give some advise, very thanks in advance. Here is the class:
    import java.net.URL;
    import java.net.URLConnection;
    import java.io.BufferedReader;
    import java.io.InputStreamReader;
    class checkHtml {
    boolean comprobarReciproco(String thisUrl, String reciproco) {
    String toReturn = null;
    boolean res = false;
    try {
    URL url = new URL(thisUrl);
    URLConnection thisConn = url.openConnection();
    BufferedReader receiver = new BufferedReader(new InputStreamReader(thisConn.getInputStream()));
    String line = new String();
    // Leemos del buffer de entrada l�nea a l�nea
    while((line = receiver.readLine()) != null) {
    if (line.indexOf(reciproco) != -1 ){
    res = true;
    break;
    } catch(Exception e) {
    System.out.println("Error:" + e);
    return res;
    public static void main(String[] args){
    checkHtml x = new checkHtml();
    System.out.println(x.comprobarReciproco("http://www.somewebpage.com/blahblah.htm","reciprocal"));

    I make the call to this proccess in the main class, with this method:
    public String [][] comprobarRecip(String arr[][], String recip){
    checkHtml check = new checkHtml();
    int j=0;
    String enlacesfinal[][] = new String[tamanyoLinks(arr)][2];
    for (int i=0; i < tamanyoLinks(arr); i++){
    // Si no est� el reciproco nos guardamos el enlace en enlacesvalidos
    if (check.comprobarReciproco(arr[0],recip) == false){
    enlacesfinal[j][0] = arr[i][0];
    enlacesfinal[j][1] = arr[i][1];
    j++;
    return enlacesfinal;
    Is in this method, where I must use the threads? Thanks a lot!

  • How to use Thread.sleep() with Java Berkeley Base API?

    Hi,
    I have explained the weird problem about the server was too busy to response to SSH but it continued to finish to run (Server not response when inserting millions of records using Java Base API
    Even I tried to increase CachSize and renice Java program, but it did not work. So, I am thinking to set sleeping time for threads in Java Berkeley Base API (using “ps” command, there were 18 light weight processes created). My program did not implement transaction or concurrency because it simply creates (millions) databases records only. Is it possible and correct to do like this in the code:
    try{
    //do create a db record
    Thread.currentThread().sleep(1000);//sleep for 1000 ms
    catch(ItrerruptedException ie){
    Thank you for your kindly suggestion.
    Nattiya

    where can I get the help doc about use AT commands in java.
    Can you give me some code example about this. It is
    difficulty to me to write it myself.You simply have to send the characters and receive the characters via the comm extension. Here is the ITU standard command set - http://ridge.trideja.com/wireless/atcommands/v250.pdf. Various modems and other devices extend this in a number of ways, you may need to find documentation specific to your device as well. But start with the standard.

  • How to use Threading Concept in oracle

    Hi all,
    I am having requirement such that i have to execute a function after insert of data in one table.due to performance issues i have to execute this function using java pooling.if anybody having idea regarding this one please share.
    I have tried by using simple javaThreading but it is not working.
    Regards,
    Ramesh.

    public static void main (String args[] ) throws Exception {
    log("main thread is: " + Thread.currentThread());
    TaskProcessor taskProcessor[] = new TaskProcessor[5];
    Thread threads[] = new Thread[taskProcessor.length];
    for (int i=0; i<taskProcessor.length; i++) {
    taskProcessor[i] = new TaskProcessor(i);
    threads[i] = new Thread(taskProcessor);
    threads[i].start();
    for (int i=0; i<taskProcessor.length; i++) {
    if (threads[i].isAlive()) {
    threads[i].join();
    * Thread to run many concurrent connections
    private static class TaskProcessor implements Runnable {
    private int number = 0;
    public TaskProcessor(int number) {
    this.number = number;
    public void run() {
    try {
    log("Thread started: " + Thread.currentThread());
    // Get a connection
    Connection conn = ConnectionFactory.getConnection();
    // Sleep and yield so that other threads can run
    Thread.yield();
    //Thread.sleep(1000);
    Thread.yield();
    Connection conn1 =ConnectionFactory.getConnection();
    log("Thread " + Thread.currentThread() + ": First Con: " + conn);
    log("Thread " + Thread.currentThread() + ": Second Con: " + conn1);
    if (conn1 != conn)
    throw new Exception("Connections dont match: " + conn + ": " + conn1);
    log("Thread " + Thread.currentThread() + " over");
    } catch (Exception e) {
    System.out.println("Exception"+e);
    private String getLeastLoadedPool() {
    if (lastNodePoolUsed == null) {
    lastNodePoolUsed = "1";
    return "1";
    if (lastNodePoolUsed.equals("1")) {
    lastNodePoolUsed = "2";
    return "2";
    else {
    lastNodePoolUsed = "1";
    return "1";
    // in connection factory get connection factory
    public synchronized static Connection getConnection() throws Exception {
    if (singletonFactory == null)
    singletonFactory = new ConnectionFactory();
    String poolId = (String) nodePoolTracker.get();
    if (poolId == null) {
    // one and store it in the thread
    poolId = singletonFactory.getLeastLoadedPool();
    nodePoolTracker.set(poolId);
    log("No Pool Associated:" + Thread.currentThread() + ", adding: " + poolId);
    return singletonFactory.getConnection(poolId);
    else {
    log("Pool Associated:" + Thread.currentThread() + ", " + poolId);
    return singletonFactory.getConnection(poolId);
    after creating this class by using lodajava i have loaded in oracle.
    Regrads,
    Ramesh

  • How to use thread pool in glassfish

    I am using jdk 1.6 with glassfish 2.1
    in admin console i found threadpools under Configuration> Thread Pools
    my questions are
    is this thread pool is accessible to programmers (just like in websphere threadpool is accessible to programmers through work manager and asynch beans)
    can I do the same thing using glassfish (eg. WorkManager wm = new WorkManager(_threadpool_) )
    or is there any other way to do this.
    Is there any way to use the threads in the threadpool to run some batch job in parallel?
    what exactly the purpose of this threadpool in glassfish, I mean it used internally bu glassfish or programmers have to use it explicitly in there code

    It is pretty straight forward. You just create an executor instance and feed it runnable objects. For example:
    import java.util.concurrent.*;
    public class ExecutorExample {
        static class Worker implements Runnable {
            public Worker(int id) {
                this.id = id;
            public void run() {
                for(int i = 0; i < 100; i++) {
                    System.out.printf("Thread %d iteration %d of 100%n", id, i);
                    try {
                        Thread.sleep(100);
                    catch(Exception e)
            private int id;
        public static void main(String[] args) {
            BlockingQueue<Runnable> queue = new ArrayBlockingQueue<Runnable>(200);
            Executor e = new ThreadPoolExecutor(10, 10, 1, TimeUnit.SECONDS, queue);
            System.out.println("Creating workers");
            for(int i = 0; i < 20; i++)
                e.execute(new Worker(i));
            System.out.println("Done creating workers");
    }

Maybe you are looking for

  • TV Guide - Is it possible to view the freeview lis...

    Hi Is is possible to view the freeview listings by 'programme type', e.g to filter the listings so they show only Films, Sports, Drama, etc I know it is possible to do this when viewing the BT Vision Freeview listings on the BT website, but I can't s

  • Want to understand SID concept...

    Hello experts, why not using the value like e. g. customer number directly in the dimension table instead of a SID? So I also could save one table (SID table)  and with this on JOIN by linking directly to the master data tables (text, attributes, hie

  • Cancel FYI notification

    Hi Consultants. Does anyone know how to stop the canceling the FYI notification after a atual notification had timed out? We have reuirement to send FYI notification after timeout the remider approval notification. i addeed FYI notification but when

  • Every time I connect my USB Disk, the airport restarts

    I am having problems getting the disk to work with the Airport Extreme. Every time I turn the disk on, it makes the Airport restart and the light turns to amber. Has anyone else had this problem? Any solutions?

  • Azureus and java error

    I just installed Azureus together with java on a fresh 0.7.1 system and when i try running azureus i get the following error message: /usr/bin/azureus: line 4: java: command not found I've got j2re-1.5.0_04-1 and azureus-2.3.0.6-1 installed. This is