SSLServerSocket + SSLSocket stops the thread ?

Hi
I'm really new to security issues. I'm trying to code a chat application with SSLServerSocket + SSLSocket as part of my project.
I can create server and client , there are no problems during connection establishment
but when connection is established and threads are started, connections for both parties is lost ?
here's my code for server side
SSLServerSocketFactory ssf = (SSLServerSocketFactory ) SSLServerSocketFactory.getDefault();
welcomeSocket = (SSLServerSocket) ssf.createServerSocket(7001);
final String[] enabledCipherSuites = { "SSL_DH_anon_WITH_RC4_128_MD5" };
welcomeSocket.setEnabledCipherSuites(enabledCipherSuites);
JOptionPane.showMessageDialog(null, "Now will wait for a connection");
connectionSocket = (SSLSocket) welcomeSocket.accept();
//create GUI
initComponents();
//create connections
initializeInputOutputStreams();
//start listening thread
new listen(inFromClient,outToClient,conversationField,serverip).start();here's my code for client side
serverip=JOptionPane.showInputDialog("Enter IP:","localhost");
SSLSocketFactory ssf = (SSLSocketFactory ) SSLSocketFactory.getDefault();     
connectionSocket = (SSLSocket) ssf.createSocket(serverip, 7001);
//create GUI
initComponents();
//create connections
initializeInputOutputStreams();
//start listening thread
new listen(inFromClient,outToClient,conversationField,serverip).start();and here's the listening thread
public class listen extends Thread
     //variables & constructor etc.
     public void run()
          while(true)
               try
               {     //read recieved message
                    recievedMessage = inFromClient.readLine();
               catch (IOException e)
                    //catch clause stuff here
               // if file transfer
               if (recievedMessage.startsWith("INCOMING FILE TRANSFER FROM REMOTE")) //here is the problem ? null pointer exception.
                    //file transfer stuff here
               else
                    //message stuff here
}I'ld really appreciate if you help

final String[] enabledCipherSuites = { "SSL_DH_anon_WITH_RC4_128_MD5" };
welcomeSocket.setEnabledCipherSuites(enabledCipherSuites);Why are you doing that? Don't. It's insecure.
JOptionPane.showMessageDialog(null, "Now will wait for a connection");
connectionSocket = (SSLSocket) welcomeSocket.accept();If this is happening in the AWT thread it will block and freeze your server GUI. Start a separate thread for accepting.
          while(true)
               try
               {     //read recieved message
                    recievedMessage = inFromClient.readLine();You're not testing for EOS here:
if (receivedMessage == null)
  break;

Similar Messages

  • How to stop the thread?

    Hi,
    How to stop the thread in java. This is my program.
    import java.net.InetAddress;
    public class ThreadPing extends Thread {
         ThreadPing(String pingIP)
              super(pingIP);
              start();
         public void run()
              try
              String pingIP = Thread.currentThread().getName();
              InetAddress inet = InetAddress.getByName(pingIP);
              Boolean get=inet.isReachable(1500);          
              if(get==true)
                   System.out.println(inet.getHostName());               
              }catch(Exception e)
         public static void main(String args[])
              for(int i=1;i<=100;i++)
                   String pingIP = "192.168.1."+i;
                   ThreadPing tp = new ThreadPing(pingIP);
    Thanks in advance.

    The simplest way to stop all the thread is to make all thread daemons and exit the program when you want them to stop.

  • URG & IMP: How does one stop the Thread.currentThread?

    hi,
    I want to stop the current thread.
    Presently teh code used Thread.currentThread.stop()
    However stop() has been deprecated
    Thread.currentThread.interrupt() doesnot seem to help.
    If I try Thread.currentThread.isAlive() post tehinterrupt, it doesnot work as desired and teh thread is still active...
    Any pointers????
    We have alreday tried using the boolean volatile varible to stop the thread as recommended by sun and since this is the currentThread, it cannot be assigned to null.
    Thanks
    Priya

    hi,
    I want to stop the current thread.
    Presently teh code used Thread.currentThread.stop()Whyever would a thread want to deliver a stop() to itself.
    Did you mean that you wanted to stop() a different thread?
    As indicated in the (depreaction) documentation for stop(), using interrupt()
    is a better idea. However, that requires you to have a protocol
    where the receiver of the interrupt then reacts in an appropriate
    manner, i.e. interrupt() can be the basis for cooperative
    thread termination; it can't merely replace a stop() call
    in an existing application without any other changes.
    >
    However stop() has been deprecated
    Thread.currentThread.interrupt() doesnot seem to
    help.
    If I try Thread.currentThread.isAlive() post
    tehinterrupt, it doesnot work as desired and teh
    thread is still active...
    Any pointers????
    We have alreday tried using the boolean volatile
    varible to stop the thread as recommended by sun and
    since this is the currentThread, it cannot be
    assigned to null.Think about what you are trying to achieve. Did you want
    to just do a Throw() out of the current method, with (or
    without )a corresponding Catch() in some outer context)
    so that the you can unwind in case of an exceptional
    condition and have the thread exit?
    >
    Thanks
    Priya

  • Stop the thread for a second

    Hi
    i want to stop the animation in my applet when the image reaches x position for only one second, then the animation should continue.
    can you help me to find the suitable function?
    thanx a lot.

    well if your using threads why not use Thread.sleep(1000);

  • How to Stop the process of Thread

    Hi,
    A process is running in a thread, which will create a file with records in it.
    I have a cancel button and if I click the button, the process should be stopped i.e. it should not allow to create the file. Is it possible to do this?
    If so, how to achieve this? Please help me in this regard...
    Thanks in Advance

    Hi,
    A process is running in a thread, which will create a
    file with records in it.
    I have a cancel button and if I click the button, the
    process should be stopped i.e. it should not allow to
    create the file. Is it possible to do this?
    If so, how to achieve this? Please help me in this
    regard...
    Thanks in AdvanceThere is no (safe) way of just stopping the thread. What you can do is have a flag in your Runnable/Thread object that you flip when you click the Cancel-button. Then in your run() method you check every now and then if the flag has been flipped. If the flag has been set you stop what you are doing and do necessary cleanup.
    Something along these lines should do it (this is just a skeleton code that won't compile, but the general idea should hopefully be clear):
    class FileCreator implements Runnable {
        private File file;
        private boolean cancelled = false;
        // Method to call when you click the Cancel-button
        public synchronized void cancel() {
            cancelled = true;
        public void run() {
            // Do whatever it is you need to do. On suitable places in the code you check if
            // the job has been cancelled. E.g.:
            try {
                if( cancelled ) {
                    return;
                // Create the file
                file = new File(...);
                if( cancelled ) {
                    return;
                // Add the records to the file:
                for( Record rec : getRecords() ) {
                    if( cancelled ) {
                        return;
                    addRecordToFile(rec, file);
                // etc, etc
            finally {
                // Do necessary cleanup if the job was cancelled, e.g.:
                if( cancelled ) {
                    if( file != null ) {
                        // The file was created before the job was cancelled. Delete it:
                        file.delete();
                    // etc, etc
    // Somewhere else in your code:
    FileCreator fc = new FileCreator();
    new Thread(fc).start();
    JButton btnCancel = new JButton("Cancel");
    btnCancel.addActionListener( new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            fc.cancel();
    ...Hope this helps!

  • Stop the running Thread

    Hi
    i am calling the thread .in the midlle of running thread i have to stop the thread .please help me .
    my senario like . I am calling the scripts . i am wating certain period to complete the script exection . if the scripts are not available its still wating for a long time . so i am using the thread to execute the scripts and (main thread )checking each duration is completed or not . if the duration completed i am stoping the thread with Thread.Stop() method . but the thread still is alive . next time when i call Thread.Start() its throwing "java.lang.IllegalThreadStateException".
    please help me this .
    Thanks in advance
    public class TestCaseScriptProcessor extends Thread {
    public String execute(){
    TestCaseScriptProcessor caseScriptProcessor = new TestCaseScriptProcessor();
    caseScriptProcessor .start();// second time throwing java.lang.IllegalThreadStateException.
    while (!isExpired) {
    caseScriptProcessor.stop();
    public void run() {
    Edited by: 849614 on Jan 17, 2013 6:17 AM
    Edited by: 849614 on Jan 17, 2013 6:22 AM

    What exactly are you trying to do? Calling Thread.stop( ) is inherently a bad idea (see the Javadocs).
    You are getting a IllegalStateException because Thread.stop( ) kills the thread, you would need to create a new thread to resume execution.
    If what you are trying to do is pause execution, you probably want to redesign your thread's tasks into smaller chunks that can be launched separately. Alternatively, have the thread check it's interrupted state and if a flag was set block on a monitor until you want it to resume execution.

  • How to stop a thread in java 1.5 on windows

    Hi All,
    I am using Java 1.5 on windows plateform. I want to stop all the threads which belongs to a particular process when the timeout occurs. In java 1.5 stop() method is depricated and interrupt method just sets the flag and does not stop the thread actually.
    Is there any way to destroy the thread permenently. I am using TheadPool Executor class.
    Regards
    Rinku Garg

    Hi,
    I am having a timer task which is scheduled to run after some fixed time interval when the process started.
    Now this timer task when started, should destroy the active threads of the request. When the request is timed out then the thread is action should termininate.
    In my case run method of particular thread had already made a call to Database through DAO when the time out occurs. So how can I set up a loop in run method which I found on google.
    thread.stop() is deprecated.
    thread.destroy() is deprecated.
    I used thread.interrupt() but it does not stops the thread.
    Please help me in this scenario.
    Regards
    Rinku Garg

  • Stopping a Thread Correctly

    Instead of using myThread.stop()
    I should do somthing like this ... correct?
    //In my Thread Dispatcher Class
    private boolean shouldStop = false;
    private Thread myThread;
    public static void setStopThread(boolean b){
    shouldStop = b;
    public boolean stopThread(){
      return shouldStop;
    public void nullifyThread(){
    myThread = null;
    //In my Thread Class
    public void run(){
    while(!myThreadDispatcherInstance.stopThread()){
      //do some Thread Work
    }//end while
    }//end run method
    myThreadDispatcherInstance.nullifyThread();Will the above code handle everything (aside for the setup and initialization part) to override the depreciation of the Thread.stop() method? Or am I missing somthing?
    oh yea also anywhere I'd need to stop the thread i'd put
    ThreadDispatcherClass.setStopThread(true);

    Looks about right, except that you need to declare setStopThead and stopThread synchronized, in order to force writing to and reading from main memory.
    NullifyThread is almost certainly pointless and unneeded.
    stopThread is a rather poor name. It sounds like it's taking an action, rather than returning a value. shouldStop() or idDone() or something would be better.
    Finally regarding "In my Thread class": Rather than extending Thread, you should implement Runnable. You're not really specializing a Thread's behavior, you're just implementing a unit of work for a thread to run.

  • Stopping a thread from running

    Hai
         I am new to java. It would be helpful for me if someone helps me out in doing this.
         Actually in my program ,I should
    i. Find out whether a particular file exists in the given directory or not.
    ii. If the file doesn't exist, my program should wait for certain timeframe and check for the same file again.
    iii. If the program cannot find the required file within the timeout specified, my application should exit.
         I have done (i) and (ii) using threads. But in the case of (iii), I came to know that stop() method is depricated.
         I am providing my code for a better understanding. Could you please let me know, what would be the best way to stop the thread from running after the timeout is reached in my program?
    Thanx in advance
    import java.io.File;
    public class Fileexists implements Runnable
    static Thread t;
    public static void main(String[] args)
         System.out.println("creation of object");     
         FileExists test = new FileExists();
         t = new Thread(test);
         t.start();
    // run method
    public void run()
         File f = new File("searchfile.txt");
         boolean b = f.exists();
    System.out.println();
    if(b == false)
    System.out.println("Required file doesnot exists");
    try
         t.sleep(20000);
    catch (InterruptedException e)
         // TODO Auto-generated catch block
         e.printStackTrace();
              t.run();
    else
    System.out.println("Required file found");
    } // end of run()
    } // end of FileExists class

    Actually your use of threads is a difference which makes no difference. The JVM starts an initial thread and runs your main(), at the end of which you start a thread and return. So you've just replaced one thread with another. There's no parallel processing.
    The t.run() at the end of your run() method won't work. A particular Thread object can only run once. It will give you an IllegalStateException.
    I can't see how multi-threading will help you with this task at all, all you need is a simple loop with a Thread.sleep in it.
    If you really want to use a separate thread or Timer to implement a timeout (as an exercise) then use Thread.interrupt() to wind up a thread. The looping thread should test with Thread.interrupted() in it's loop condition, if it's in sleep() when interrupted an InterruptedException will be thrown which you should catch and allow to break the loop and let the thread terminate.
    So your loop structure looks like:
    try {
    while(!Thread.interrupted()) {
        ...  do your test
        Thread.sleep(.....);
      System.out.println("Thread terminated by detecting interrupted");
      } catch(InterruptedException ex)  {
         System.out.println("Thread interrupted from sleep");
    You can get the Thread for the main thread simply by storing Thread.currentThread() in a Thread reference.
    I'd suggest using a java.util.Timer to launch your time-out and leave the loop on the main thread started by the JVM.

  • How to stop a thread forcefully. do reply urgent

    i would like to stop the thread . i have used stop() method and also i have tested by giving the threadname = null. but these two not worked . how to stop thread forcefully. urgent.
    with regards

    There is no direct way to stop the thread forcefully. If you have implemented the thread, modify the code so as to break on some flag.
    i.e.
    public void run()
    while (keepRunning)
    ...do some stuff here
    and provide some way to set the boolean keepRunning as false. The loop will exit and the thread will also be destroyed.

  • Start/Stop a thread dynamically.

    i have an attribute Thread t;
    i initialize it as
    t = new Thread(){
         public void run(){
              try{
                   System.out.println("do something");
                   sleep(10000);  // sleep a while
              catch(Exeception e){}
    };i invoke it by t.start(); and stop it by t.sopt(), but i failed in t.start() to start it again
    How could i start and stop it externally without re-new the object ?

    The stop() method should not be used.
    Instead you might want to try the pattern:
    volatile Thread aThread=null;
    public void run() {
    aThread = this.currentThread();
    while(aThread!=null) {
    //sleep
    and write a method to set aThread to null to stop the thread.

  • Cannot stop this thread...

    Hello, I have the following code:boolean kill = false;
    public void go() {
       while (!kill) {
            sleep(3000);
            //do stuff.
    public void stopThread() {
        kill = true;
    }This code doesn't stop it. I cannot seem to stop this thread with the boolean variable. I think its because I have the thread asleep but I'm not sure. How can you stop a thread that sleeps for a period of time?
    Thanks.

    Here's my code: class CreateGui {
    Vector<Thread> threads = new Vector<Thread>();
    //lots of stuff here...
    public void start() {
         Runnable runner;
    runner = new RunThreads();
         Thread t = new Thread(runner);
         t.setName(_code);
         t.start();
         threads.add(t);
    public void stop() {
         RunThreads r = new RunThreads();     
         r.stopThread();     
    class RunThreads implements Runnable {     
         boolean kill = false; 
    public void run() {
         go();
    public void go() {
       while (!kill) {
         try {
         Thread.sleep(3000); .
         } //try          
         catch (InterruptedException ex) {
         ex.printStackTrace(); }
             //do stuff here...     
              } //while
    } //method go
    public void stopThread() {
         kill = true;
    }The user clicks a button to start a thread, and then clicks another button to stop the thread. With this program I am supposed to have up to 26 threads running at once. I know I may not be doing things totally correctly, but that is what I'm trying to accomplish. I can take the harshest criticism: )

  • How to stop a threads that makes I/O calls ?

    Hi,
    I've a business method that calls a Stored Procedure and makes lots of calculations. This method works inside its own thread, because I do not want to stop the GUI from accepting user actions.
    My problem is : this method may take from 5 minutes to 1 hour to process, depending on the size of the input. Sometimes, for any reason at all, the user may want to stop this execution (pressing a button on the GUI). How can I safely stop the thread ?
    I know I should not use stop() and suspend() because they are deprecated. And I do not use loops (remember it calls only a StoredProcedure that makes all processing), so I cannot use a variable nor interrupt(), because they do not work.
    Do you know any other way to stop this thread's execution ? By the way destroy() is not implemented.
    Thanks and regards.
    Bruno

    Are you saying that the 5 minutes to an hour is all spent in the stored procedure?
    If so the only real solution is to kill the statement - I'm not sure how the DB will handle that, but it will certainly free up your cycles.
    To do that without violating encapsulation, you just need to keep a reference to an object that knows something about the DB connection - you don't have to actually pass around the JDBC objects.
    Consider an object like this:
    public class DoLongProcedure {
       private Statement dbStatement;
       public double doLongCalculation() {
          dbStatement.execute(...);
          // etc
       public void interruptCalculation() {
          dbStatement.close();
    }You create an instance of this object and call its doLongCalculation() method to start everything. You have a reference to this object somewhere, because you are waiting for a response. When the user wants to cancel the process you just call the interruptCalculation() method.
    You have not violated your separation of functionality - if you find a new way to stop the process without killing the statement later, you just reimplement that method.

  • Can't stop synchronized threads with I/O read and write

    I have two synchronized threads which doing read and write from and into a file.
    One thread called "reader" which does reading, encoding, etc from a source file and puts its output in a pre-defined variable. Another called "writer" which puts the reader's output into a file ( not the source file ). Both thread will notify each other when they've finished each of their part. It's similiar to CubyHole example of Java Tutorial example from Sun.
    But somehow it seems like the threads keep spawning and won't die. Even if the source file has been all read and the data has been fully written, calling interrupt(), return, etc has no effect. The threads will keep running untill System.exit() called.
    Is it because the threads were blocked for I/O operation and the only way to kill them is to close the I/O ?
    To be honest, it's not only stop the threads that I want to, I also want to somehow pause the threads manually in the middle of the process.
    Is it possible ?
    Cheers.!!!

    The example code for the problem using 4 classes called :
    - libReadWrite ( class holding methods for aplication operations )
    - reader ( thread class responsible for reading data )
    - writer ( thread class responsible for writing data )
    - myGUI ( user interface class )
    All of them written in different file.
    // libReadWrite
    pubic class libReadWrite {
    private boolean dataReady;
    private String theData;
    //read data
    public synchronized void read(String inputFile) {
    while (dataReady == true) {
    try {
    wait();
    } catch (InterruptedException ex) {}
    RandomAccessFile raf = new RandomAccessFile(inputFile, "r"); // I'm using raf here because there are a lot of seek operations
    theData = "whatever"; // final data after several unlist processes
    dataReady = true;
    notifyAll();
    public synchronized void write(String outputFile) {
    while (dataReady == false) {
    try {
    wait();
    } catch (InterruptedException ex) {}
    DataOutputStream output = new DataOutputStream(new FileOutputStream(outputFile, true));
    output.writeBytes(theData);
    dataReady = false;
    notifyAll();
    //Reader
    public class reader extends Thread {
    private libReadWrite myLib;
    private String inputFile;
    public reader (libReadWrite myLib, String inputFile) {
    this.myLib = myLib;
    this.inputFile = inputFile;
    public void run() {
    while (!isInterrupted()) {
    myLib.read(inputFile); <-- this code running within a loop
    return;
    public class writer extends Thread {
    private libReadWrite myLib;
    private String outputFile;
    public writer (libReadWrite myLib, String outputFile) {
    this.myLib = myLib;
    this.outputFile = outputFile;
    public void run() {
    while (!isInterrupted()) {
    myLib.write(outputFile); <-- this code running within a loop
    try {
    sleep(int)(Math.random() + 100);
    } catch (InterruptedException ex) {}
    return;
    //myGUI
    public class myGUI extends JFrame {
    private libReadWrite lib;
    private reader readerRunner;
    private writer writerRunner;
    //Those private variables initialized when the JFrame open (windowOpened)
    libReadWrite lib = new libReadWrite();
    reader readerRunner = new reader("inputfile.txt");
    writer writerRunner = new writer("outputfile.txt");
    //A lot of gui stuffs here but the thing is below. The code is executed from a button actionPerformed
    if (button.getText().equals("Run me")) {
    readerRunner.start();
    writerRunner.start();
    button.setText("Stop me");
    } else {
    readerRunner.interrupt();
    writerRunner.interrupt();
    }

  • Stopping native-threads

    hi all,
    how can i stop native (hanging) threads?
    i see that many people have this question but i can't find any real solution.
    all the time sun said we should us cancel-flags in a loop in the thread. but how to do this when the threads was written from other with native code (the most original io-classes from sun , eg. java.net.UrlConnection)?!
    look at the following code example:
    in linux and mac os-x the timeout for dns-lookups needs between 40 and 60 seconds. but what if you don't like to wait so long?! if you like to test many 1000 urls (internal and external urls mixed)
    latest with jdk 1.4 you will get almost internel-jvm-error ending in a java-crash if you test in a loop much urls.
    but please! if somebody has a thread-save-soluton please post it!
    thx
    oliver scorp
    code-example:
    ublic final class Test1 {
    private boolean urlErr = false;
    private String urlErrMsg = null;
    private int urlTimeout = 5;
    public final class TestUrlConnection extends Thread{
    private String myUrl = null;
    public TestUrlConnection(String parMyUrl) {
    super();
    myUrl = parMyUrl;
    public void run(){
    try{
    if (myUrl == null)
    return;
    java.net.URL u = new java.net.URL(myUrl);
    java.net.URLConnection uc = u.openConnection();
    uc.connect(); // 40 sec timout in linux when url not can be connected !!!
    // 60 sec timeout in MAC OS-X !!!
    // 1 sec timeout in Windows !!! (so, this example maybe doesn't work there!)
    }catch(Exception e){
    urlErr = true;
    urlErrMsg = e.toString();
    public Test1() {
    super();
    public static void main (String args[]) {
    Test1 myProg = new Test1();
    myProg.myTest1();
    public void myTest1() {
    try{
    String s = "http://www.apache.org";
    TestUrlConnection tuc = new TestUrlConnection(s);
    tuc.start();
    tuc.join(urlTimeout * 1000);
    if (tuc.isAlive()){
    tuc.stop(); //searching for an alterNATIVE
    //is extrem instable in jdk 1.4!
    //(get almost internal errors in jvm if you have many 100 test-threads)
    //tuc.interrupt(); //doesn't work by native (hanging) threads
    //tuc = null; //doesn't stop the thread
    urlErr = true;
    urlErrMsg = "Connection timeout!";
    if (urlErr)
    System.out.println(urlErrMsg);
    else
    System.out.println("Connection ok");
    }catch(Exception e){
    System.out.println(e.toString());

    the question was: how to end native threads - threadsave (without using the 'deprecated' stop-methode)?!So you have a C method (not Java) in which you created a thread that runs C code (not Java) and it is indeed running, not blocked, and you wish to end it?
    Seems like a bad design and bad idea to me, because it is very likely that it will cause memory leaks, and since it it hard to cause it to stop at arbritrary points in its execution it will also be hard to use an automated tool to track down those leaks.
    But if you have already dealt with all of those issues then you could stop it. The answer to how is specific to the thread library that you are using. So at the very least you would have to specify that. And since this particular topic has nothing to do with java you might find an answer on another list/forum/group faster.
    Despite all of the above, if the thread touches java in any way then I would say that trying to stop it arbritrarily is going to be a really bad idea. Java isn't set up for that. And at the very least you will end up with memory leaks (with no way to get rid of them, since they are likely to be internal to the JVM.) And that would be the best outcome. It is also possible that it would make the JVM unstable and I can't imagine any application where that is going to be a good thing.

Maybe you are looking for

  • How to pick up the latest report instance of a schedueld report

    Hi, I am supporting a custom application (.NET), which has to pick up the latest report instance by accepting the Report ID. At times, the application does seems to be pick up the wrong (older) instance. This is not happening all the times but certai

  • Syncing iTunes on a mac and Outlook on a PC

    Hi, I have a quick question. I have my music, videos and photos sitting on my mac at home. My outlook is on my work windows PC. If I buy an iPhone and want to sync with the mac for the music etc. and work my pc for outlook would this be possible? Tha

  • How Can I Restrict Unwanted Incoming Call in iphone 4

    How Can I Restrict Unwanted Incoming Call. Help Me

  • Printing Polish from Unicode ECC system

    Hi, to print Polish characters as SAPscript, ABAP-list or SmartForms from a ECC 6.0 already converted in Unicode, is it right way cascading fonts, SAPWIN, SAPSprint, ecc. ? Or... can I use "classic" HPLJ4000 device type with access method D? My ECC s

  • Loop to validate all field before sending / printing

    Hi Guys, I have try for the last two days to script a loop that can check if all field are "non null" brefore sending the form through email or before printing. I tried to loop through the node class : exclGroup but I could not get it to work ... Doe