Threaded Socket activated by JButton

Hi all,
I am trying to create an FTP server with GUI. I would like to run and stop the server from command line and from the GUI. My problem is that when i press the button to start the server my GUI freezes. My server is using threads in order to serve multiple clients. Does anyone have any idea how I should do that ?
Thanks
Section5

I am going to have to do a similar thing as well.
The way I more that likely will go about is to
have a JButton create a new thread for my ServerListener.
So that i be able to press my button.
My serverlistener will listen open a serverSocket and listen
and create a new connectionHandler for each new client that
needs info etc.
hope it helps
let us know.

Similar Messages

  • Multi thread socket

    Hi all
    I have an distributed application .I use jboss as a application server.I 've done a session bean that create a class containing a multi thread socket .I wonder if it's right does a multi thread socket or jboss does the multithreading by itself.
    Regards
    Gio

    There is no such thing as a multi thread socket. There are just sockets. How you use them is up to you.

  • Is thread still active after main method exits?

    Hi All,
    Yesterday we were discussing. wether it is possible for a thread to be active even after the main method, from which it was spawned, exits.
    any comments?

    Hello,
    If you start a thread from the main() method and then return from main(), the thread will remain running. Just try it out:
    public class Test
        implements Runnable
        public static void main(String[] args)
            Thread t = new Thread(new Test());
            t.start();
            System.out.println("Returning from main()");
        public void run()
            try
                Thread.sleep(5000);     // Wait for 5 seconds
                System.out.println("Hello, I'm still here!");
            catch (InterruptedException ie)
                ie.printStackTrace();
    }Note: If you exit main() using System.exit(), all threads will be killed!
    Jesper

  • Start 2 Threads by clicking 1 JButton

    I want to change 2 JPanels in a CardLayout before the Action of this JButton is performed.
    I tried to add a second ActionListener for this Button but both ActionListener used the same Thread so there was no visual effect :(
    What am I to do to fix this problem?

    First of all thank you for your help.
    I already tried to start a second thread:
         public class showWait extends Thread {
              CardLayout textLayout;          
              public showWait(CardLayout tL)
                   textLayout=tL;
              public void run()
                   textLayout.show(textContainer,"STANDBY");
              public CardLayout getLayout()
                   return textLayout;
    public void actionPerformed(ActionEvent evt) {
         showWait sw = new showWait(textLayout);
         sw.run();
         textLayout=sw.getLayout();
    myCalculation();
    textLayout.show(textContainer,"HTML");
    But it doesn't work :(
    The change of the CardLayout in the showWait thread is not displayed.
    Should I declare the Calculation as an other class extends Thread?
    That would not be easy because I would have to clone many objects.
    Jörn

  • How to find db threads were active at particular time

    How can we find the number of oracle
    database threads were for this period. Can any one tell me how to
    determine these counts?

    Hello,
    DBA_HIST_ACTIVE_SESS_HISTORY displays the history of the contents of the in-memory active session history of recent system activity. This view contains snapshots of V$ACTIVE_SESSION_HISTORY.Kind regards
    mohamed El Azab

  • T Box: help with coaxial vs threaded wall socket issue

    Hi there! Hope someone out there can help me or point me in the right direction! I purchased a T Box Entertainer Bundle for my new rental residence, and after moving in yesterday I received my T Box today. All excited about plugging in the T Box and catching up on some viewing from the past few days, but it seems that while my new place has a TV connection, it is not the standard coaxial type! Arrrggghhhh! There is the usual phone connection attached to the wall, and beneath that a wall plate branded with Telstra (upside down!) and instead of the usual coaxial connection there is a threaded socket with a small female pin port. Just to satisfy my own curiosity I did try and plug the coaxial cable which came with the T Box to the socket, but obviously it doesn't fit either with male or female connections. A bit of slow online searching later (I also don't have my internet or landline connected as yet, and am in a mobile blackspot to compound the problem) and I am pretty sure what I have in the wall is actually a cable or Foxtel connection. From what I've read, if I get an adapter I will still need to get the whole thing rewired to an antenna...is this correct? Or is it possible that as the T Box has Foxtel anyway that either an adapter or a different cable would work?Or is this something that the tech can do when they come out to connect my landline and ADSL2+? Fingers crossed there is a reasonable solution to this as with being in a rental my options are limited!Many thanks in advance to you all.

    AlanM52 wrote:
    That wall plate is for Foxtel – not FTA. You will not be able to get BigPond cable in that complex. DIY I would look at smaller caravan type antenna (window/balcony) and some cable. Not long ago ALDI were selling “active” indoor antennas for about $30-40 bucks, if you can get one and no-go just return.Thanks Alan...but if that is the case, why doesn't Foxtel have any history over the past 6 years of anyone ever having Foxtel in this unit? The wall plate is not Foxtel branded, but Telstra branded. The complex is probably 50 years old, but the reno is a lot more recent - say, a couple of years maximum. Also, Foxtel are telling me that only a couple of people in the last 6 years have ever had Foxtel anywhere in the entire 40-odd apartment complex which is over two separate buildings...why would there be backboned Foxtel cable if no one is using it? Foxtel use Telstra cable to deliver their content - I get that. But if practically no one is using the cable for Foxtel - what ARE they using it for? It doesn't seem to be broadband as I was told only ADSL2+ is available to me...
    There are no visible external antennas, and if all the units have been cabled, why would this one be different? I find it difficult to believe that all the residents are having to rely on rabbit-ears or window antennas simply to get FTA!There are a lot of large metal structures around this area, as well as other frequency-interference objects,so I am surmising that this would be the reason the building has been backboned cabled. But hey - just guessing here... So really - who can I ask about what is actually connected to this address? Foxtel say it's not them and tell me to ask Telstra, Telstra SHOP staff (not the good folk here) are telling me they cant help me in person and I have to call customer service from home,  I don't have a landline or my ADSL connected yet so can only use my mobile for which I have limited service while I wait for the delivery of a 3G home booster thingy. Can anyone tell me to which Telstra department I should be directing my enquiry to?At the moment I have now useless T-Box sitting here begging to be used, which I purchased in good faith on the advice I received from a Telstra provider that I have the necessary and correct connections for it to work! Seeing as they appeared to have access to the information required to check on the service availability to this address and specifically this apartment - who do I need to contact to get more information?At the very least, put me out of my misery - if I have to install an antenna, so be it, but I need to be sure this is the only option available to me before I go through the process of getting landlord, body corporate, aand whoeverelse persmission, not to mention the considerable expense! Please - someone, anyone at Telstra - tell me who I need to contact, to find out once and for all, with absolute certainty what this connection is for!  Sorry if I sound desperate...everyone has been very helpful here so far, but I'm going crazy trying to figure this out!

  • BPEL Client API - Query Domain for Number of Active Threads ?

    Hi,
    Is there a method to query the number of active threads within the domain ? i.e. the same value displayed under Thread Allocation Activity shown on http://localhost/BPELConsole/default/domain.jsp?mode=thread
    I've browsed the API docs but can't find a way to do this... I might have missed something thought.
    Cheers,
    Rob

    Thanks Marc.
    How would I go about getting a domain handle ? The bit I'm stuck on in obtaining the initial authenticated connection to the server. The ngThreadInfo code does this:
    Server server = ServletUtils.getServer( request, response );
    String token = server.getServerAuth().getToken();
    and I guess the request/response vars provide the security context in which the getServerAuth operates ?
    Which API functions can I embed in a BPEL process to connect to the server and subsequently obtain the domain handle ?
    Cheers,
    Rob J.

  • Nasty memory leak using sockets inside threads

    In short, any time I create or use a socket inside a worker thread, that Thread object instance will never be garbage collected. The socket does not need to be connected or bound, it doesn't matter whether I close the socket or not, and it doesn't matter whether I create the Socket object inside the thread or not. As I said, it's nasty.
    I initially encountered this memory leak using httpclient (which creates a worker thread for every connect() call), but it is very easy to reproduce with a small amount of stand-alone code. I'm running this test on Windows, and I encounter this memory leak using the latest 1.5 and 1.6 JDK's. I'm using the NetBeans 5.5 profiler to verify which objects are not being freed.
    Here's how to reproduce it with an unbound socket created inside a worker thread:
    public class Test {
         public static class TestRun extends Thread {
              public void run() {
                   new Socket();
         public static void main(String[] strArgs) throws Exception {
              for(;;) {
                   (new TestRun()).start();
                   Thread.sleep(10);
    }Here's how to reproduce it with a socket created outside the thread and used inside the worker thread:
    public class Test {
         public static class TestRun extends Thread {
              Socket s;
              public TestRun(Socket s) { this.s = s; }
              public void run() {
                   try {
                        s.bind(new InetSocketAddress(0));
                        s.close();
                   } catch(Exception e) {}
         public static void main(String[] strArgs) throws Exception {
              for(;;) {
                   (new TestRun(new Socket())).start();
                   Thread.sleep(10);
    }Here's how to reproduce it implementing Runnable instead of extending Thread:
    public class Test {
         public static class TestRun implements Runnable {
              public void run() {
                   Socket s = new Socket();
                   try { s.close(); } catch(Exception e) {}
         public static void main(String[] strArgs) throws Exception {
              for(;;) {
                   (new Thread(new TestRun())).start();
                   Thread.sleep(10);
    }I've played with this a lot, and no matter what I do the Thread instance leaks if I create/use a socket inside it. The Socket instance gets cleaned up properly, as well as the TestRun instance when it's implementing Runnable, but the Thread instance never gets cleaned up. I can't see anything that would be holding a reference to it, so I can only imagine it's a problem with the JVM.
    Please let me know if you can help me out with this,
    Sean

    Find out what is being leaked. In the sample programs, add something like this:
        static int loop_count;
            while (true) {
                if (++count >= 1000) {
              System.gc();
              Thread.sleep(500); // In case gc is async
              System.gc();
              Thread.sleep(500);
              System.exit(0);
            }Then run with java -Xrunhprof:heap=sites YourProgram
    At program exit you get the file java.hprof.txt which contains something like this towards the end of the file:
              percent          live          alloc'ed  stack class
    rank   self  accum     bytes objs     bytes  objs trace name
        1  0.47%  0.47%       736    5       736     5 300036 char[]
        2  0.39%  0.87%       616    3       616     3 300000 java.lang.Thread
        3  0.30%  1.17%       472    2       472     2 300011 java.lang.ThreadLocal$ThreadLocalMap$Entry[]
        4  0.27%  1.43%       416    2       416     2 300225 java.net.InetAddress$Cache$Type[]See, only three live Thread objects (the JVM allocates a few threads internally, plus there is the thread running main()). No leak there. Your application probably has some type of object that it's retaining. Look at "live bytes" and "live objs" to see where your memory is going. The "stack trace" column refers to the "TRACE nnnnn"'s earlier in the file, look at those to see where the leaked objects are allocated.
    Other quickies to track allocation:
    Print stats at program exit:
    java -Xaprof YourProgram
    If your JDK comes with the demo "heapViewer.dll" (or
    heapViewer.so or whatever dynamic libraries are called on your system):
    java -agentpath:"c:\Program Files\Java\jdk1.6.0\demo\jvmti\heapViewer\lib\heapViewer.dll" YourProgram
    Will print out statistics at program exit or when you hit Control-\ (Unix) or Control-Break (Windows).

  • A problem with threads

    I am trying to implement some kind of a server listening for requests. The listener part of the app, is a daemon thread that listens for connections and instantiates a handling daemon thread once it gets some. However, my problem is that i must be able to kill the listening thread at the user's will (say via a sto button). I have done this via the Sun's proposed way, by testing a boolean flag in the loop, which is set to false when i wish to kill the thread. The problem with this thing is the following...
    Once the thread starts excecuting, it will test the flag, find it true and enter the loop. At some point it will LOCK on the server socket waiting for connection. Unless some client actually connects, it will keep on listening indefinatelly whithought ever bothering to check for the flag again (no matter how many times you set the damn thing to false).
    My question is this: Is there any real, non-theoretical, applied way to stop thread in java safely?
    Thank you in advance,
    Lefty

    This was one solution from the socket programming forum, have you tried this??
    public Thread MyThread extends Thread{
         boolean active = true;          
         public void run(){
              ss.setSoTimeout(90);               
              while (active){                   
                   try{                       
                        serverSocket = ss.accept();
                   catch (SocketTimeoutException ste){
                   // do nothing                   
         // interrupt thread           
         public void deactivate(){               
              active = false;
              // you gotta sleep for a time longer than the               
              // accept() timeout to make sure that timeout is finished.               
              try{
                   sleep(91);               
              }catch (InterruptedException ie){            
              interrupt();
    }

  • Issue with Ftp Client / Server using Sockets

    I have developed a Ftp Client and a Ftp Server. The client Connects to the Ftp Server and sends files to the ftp server. It is a multi threaded server and can have multiple clients connecting to it.
    If a client goes down...the server waits till the client comes up
    Similarly the client waits if a server goes down and reconnects when the server is again up and running
    i am having a strange issue here. When two clients go down and reconnect to the server...They take a long time to connect and transferring of files takes a long time...
    Other wise in all other scenarios the duo work properly.
    Any feedback and suggestion about this strange issue from all you java gurus out there will be deeply appreciated.
    Here is the client code
    import java.net.*;
    import java.net.Socket;
    import java.net.InetAddress;
    import java.io.*;
    import java.io.File;
    import java.util.*;
    import java.lang.*;
    import java.lang.Object;
    import javax.crypto.*;
    import java.util.regex.*;
    import javax.crypto.spec.PBEKeySpec;
    import javax.crypto.spec.PBEParameterSpec;
    import java.security.spec.AlgorithmParameterSpec;
    import java.security.spec.KeySpec;
    import java.io.InputStream;
    import java.io.IOException;
    import java.io.OutputStream;
    import java.io.File.*;
    import java.nio.channels.FileLock;
    public class  FTPClient {
         public static void main(String[] args) throws Exception
              Timer timer = new Timer("Test Timer");
              timer.scheduleAtFixedRate(new TimerTask()
                   private int counter = 0;
                                            public void run() {
                                                                     try     {                                                                                
                                                                              System.out.println(counter++);
                                                                               Socket soc=new Socket("xxx.x.x.xx",5217);
                                                                               System.out.println("Socket Initialised.");          
                                                                               transferfileClient t=new transferfileClient(soc);
                                                                               t.SendFile();
                                                                               System.out.println("run complete.");                                                                           
                                                                          catch(Exception ex)
                                                           }, 10000, 40000);
         static class transferfileClient
         Socket ClientSoc;
         DataInputStream din;
         DataOutputStream dout;
         BufferedReader br;
         transferfileClient(Socket soc)
              try
                   ClientSoc=soc;
                   din=new DataInputStream(ClientSoc.getInputStream());
                   dout=new DataOutputStream(ClientSoc.getOutputStream());
                   br=new BufferedReader(new InputStreamReader(System.in));
              catch(Exception ex)
         //encrypto routine starts
    class DesEncrypter {
           Cipher ecipher;
            Cipher dcipher;   
            // 8-byte Salt
            byte[] salt = {
                (byte)0xA9, (byte)0x9B, (byte)0xC8, (byte)0x32,
                (byte)0x56, (byte)0x35, (byte)0xE3, (byte)0x03
            // Iteration count
            int iterationCount = 19;   
            DesEncrypter(String passPhrase) {
                try {
                             // Create the key
                             KeySpec keySpec = new PBEKeySpec(passPhrase.toCharArray(), salt, iterationCount);
                             SecretKey key = SecretKeyFactory.getInstance(
                             "PBEWithMD5AndDES").generateSecret(keySpec);
                             ecipher = Cipher.getInstance(key.getAlgorithm());
                             dcipher = Cipher.getInstance(key.getAlgorithm());   
                             // Prepare the parameter to the ciphers
                             AlgorithmParameterSpec paramSpec = new PBEParameterSpec(salt, iterationCount);   
                             // Create the ciphers
                             ecipher.init(Cipher.ENCRYPT_MODE, key, paramSpec);
                             dcipher.init(Cipher.DECRYPT_MODE, key, paramSpec);
                } catch (java.security.InvalidAlgorithmParameterException e) {
                } catch (java.security.spec.InvalidKeySpecException e) {
                } catch (javax.crypto.NoSuchPaddingException e) {
                } catch (java.security.NoSuchAlgorithmException e) {
                } catch (java.security.InvalidKeyException e) {
            // Buffer used to transport the bytes from one stream to another
            byte[] buf = new byte[1024];   
            public void encrypt(InputStream in, OutputStream out) {
                try {
                    // Bytes written to out will be encrypted
                    out = new CipherOutputStream(out, ecipher);   
                    // Read in the cleartext bytes and write to out to encrypt
                    int numRead = 0;
                    while ((numRead = in.read(buf)) >= 0) {
                        out.write(buf, 0, numRead);
                    out.close();
                } catch (java.io.IOException e) {
            public void decrypt(InputStream in, OutputStream out) {
                try {
                    // Bytes read from in will be decrypted
                    in = new CipherInputStream(in, dcipher);   
                    // Read in the decrypted bytes and write the cleartext to out
                    int numRead = 0;
                    while ((numRead = in.read(buf)) >= 0) {
                        out.write(buf, 0, numRead);
                    out.close();
                } catch (java.io.IOException e) {
    }     //encryptor routine ends     
         void SendFile() throws Exception
                   try
                   String directoryName; 
                   // File object referring to the directory.
                   String[] files;        // Array of file names in the directory.        
                   //directory = new File ( "C:\\FTP\\" ) ; 
                   File directory1 = new File("C:\\FTP");
                        boolean successmk = directory1.mkdir();
                        if (!successmk) {
                             // Directory creation failed /Already Exists
                        File directory = new File("C:\\FTP\\ftpc");
                        boolean successmk1 = directory.mkdir();
                        if (!successmk1) {
                             // Directory creation failed /Already Exists
                   //directory = new File ( "E:\\FTP-encrypted" ) ;           
                if (directory.isDirectory() == false) {
                    if (directory.exists() == false)
                       System.out.println("There is no such directory!");
                    else
                      System.out.println("That file is not a directory.");
                else {
                    files = directory.list();
                    System.out.println("Files in directory \"" + directory + "\":");
                    for (int i = 0; i < files.length; i++)
                             String patternStr = "xml";
                             Pattern pattern = Pattern.compile(patternStr);
                             Matcher matcher = pattern.matcher(files);
                             boolean matchFound = matcher.find();
                                       if (matchFound) {                                   
                                       System.out.println(" " + files[i]);                                        
                                       String filename;
                                       filename=files[i];                                   
                                       File f=new File(directory,filename);
                                       FileLock lock = null;                                   
                                       FileOutputStream fos = new FileOutputStream(f, true);
                                       lock = fos.getChannel().tryLock();
                                                 if (lock == null) {
                                                 System.out.println(" Failed to get the file lock: means that the file is locked by other instance.");
                                                 fos.close();
                                                 else
                                                                     InetAddress addr = InetAddress.getLocalHost();                                                                      
                                                                               // Get IP Address
                                                                               //byte[] ipAddr = addr.getAddress();
                                                                               String ip= addr.toString();                                                                      
                                                                               // Get hostname
                                                                               //String hostname = addr.getHostName();
                                       System.out.println(" Lock Acquired.");
                                       lock.release();
                                       fos.close();
                                       dout.writeUTF("SEND");
                                            dout.writeUTF(ip);
                                       dout.writeUTF(filename);
              //String msgFromServer=din.readUTF();          
    DesEncrypter encrypter = new DesEncrypter("My Pass Phrase!");
    // Encrypt
              FileInputStream fino=new FileInputStream(f);
              encrypter.encrypt(fino,
    new FileOutputStream("ciphertext.txt"));               
              fino.close();
              FileInputStream fin=new FileInputStream("ciphertext.txt");          
              int ch;
              do
                   ch=fin.read();
                   dout.writeUTF(String.valueOf(ch));
              while(ch!=-1);
              fin.close();          
              String option;
                        option=din.readUTF();
                             if((option.compareTo("Delete")==0))     
                                  boolean success = (new File("ciphertext.txt")).delete();
                                  boolean success1 = f.delete();
                                  if (success) {
                                  System.out.println("File Sent ...");
                                  if (success1) {
                                  System.out.println("--File deleted from Client ...");
         for (int j = 0; j < 999999999; j++){}
                                       }//pattermatch loop ends here
    else
                             { //System.out.println("   " + "Not an XML file-------->" +files[i]);
    for (int jb = 0; jb < 111999999; jb++){}
              }// for loop ends here for files in directory
                   }//else loop ends for directory files listing               
         System.out.println("sendfile finished...");
         return;
         }               catch(Exception ex)          {ex.printStackTrace();}                    
         }//sendfile ends here     
         public void displayMenu() throws Exception
                   System.out.println(" Send File");                    
                        SendFile();
                        return;          
    And here is the server code...
    import java.net.*;
    import java.io.*;
    import java.util.*;
    import java.util.Date;
    import java.text.SimpleDateFormat;
    import java.text.DateFormat;
    import java.text.Format;
    import java.lang.Object;
    import java.lang.*;
    import javax.crypto.*;
    import javax.crypto.spec.PBEKeySpec;
    import javax.crypto.spec.PBEParameterSpec;
    import java.security.spec.AlgorithmParameterSpec;
    import java.security.spec.KeySpec;
    public class FTPServer
    {     public static void main(String args[]) throws Exception
         {     ServerSocket soc=new ServerSocket(5217);
              System.out.println("FTP Server Started on Port Number 5217");
              while(true)
                   System.out.println("Waiting for Connection ...");
                   transferfile t=new transferfile(soc.accept());               
    class transferfile extends Thread
         Socket ClientSoc;
         DataInputStream din;
         DataOutputStream dout;     
         transferfile(Socket soc)
         {     try
              {     ClientSoc=soc;                              
                   din=new DataInputStream(ClientSoc.getInputStream());
                   dout=new DataOutputStream(ClientSoc.getOutputStream());
                   System.out.println("FTP Client Connected ...");
                   System.out.println("External IP of Client ..." + ClientSoc.getInetAddress());
                   //System.out.println("FTP Client Connected ..." + ClientSoc.getRemoteSocketAddress());
                   start();               
              catch(Exception ex)
    //encrypto routine starts
    class DesEncrypter {
            Cipher ecipher;
            Cipher dcipher;   
            // 8-byte Salt
            byte[] salt = {
                (byte)0xA9, (byte)0x9B, (byte)0xC8, (byte)0x32,
                (byte)0x56, (byte)0x35, (byte)0xE3, (byte)0x03 };   
            // Iteration count
            int iterationCount = 19;   
           DesEncrypter(String passPhrase) {
                try {
                    // Create the key
                    KeySpec keySpec = new PBEKeySpec(passPhrase.toCharArray(), salt, iterationCount);
                    SecretKey key = SecretKeyFactory.getInstance(
                        "PBEWithMD5AndDES").generateSecret(keySpec);
                    ecipher = Cipher.getInstance(key.getAlgorithm());
                    dcipher = Cipher.getInstance(key.getAlgorithm());   
                    // Prepare the parameter to the ciphers
                    AlgorithmParameterSpec paramSpec = new PBEParameterSpec(salt, iterationCount);   
                    // Create the ciphers
                    ecipher.init(Cipher.ENCRYPT_MODE, key, paramSpec);
                    dcipher.init(Cipher.DECRYPT_MODE, key, paramSpec);
                } catch (java.security.InvalidAlgorithmParameterException e) {
                } catch (java.security.spec.InvalidKeySpecException e) {
                } catch (javax.crypto.NoSuchPaddingException e) {
                } catch (java.security.NoSuchAlgorithmException e) {
                } catch (java.security.InvalidKeyException e) {
            // Buffer used to transport the bytes from one stream to another
            byte[] buf = new byte[1024];   
            public void encrypt(InputStream in, OutputStream out) {
                try {
                    // Bytes written to out will be encrypted
                    out = new CipherOutputStream(out, ecipher);   
                    // Read in the cleartext bytes and write to out to encrypt
                    int numRead = 0;
                    while ((numRead = in.read(buf)) >= 0) {
                        out.write(buf, 0, numRead);
                    out.close();
                } catch (java.io.IOException e) {
            public void decrypt(InputStream in, OutputStream out) {
                try {
                    // Bytes read from in will be decrypted
                    in = new CipherInputStream(in, dcipher);   
                    // Read in the decrypted bytes and write the cleartext to out
                    int numRead = 0;
                    while ((numRead = in.read(buf)) >= 0) {
                        out.write(buf, 0, numRead);
                        //added later on
                        in.close();                    
                    out.close();
                } catch (java.io.IOException e) {
    }     //encryptor routine ends
    //not implemented right now as we arent using the ftp server to download stuff...can be activated later on if we want
         void SendFile() throws Exception
              String filename=din.readUTF();
              File f=new File(filename);
              if(!f.exists())
                   dout.writeUTF("File Not Found");
                   return;
              else
              {     dout.writeUTF("READY");
                   FileInputStream fin=new FileInputStream(f);
                   int ch;
                   do
                        ch=fin.read();
                        dout.writeUTF(String.valueOf(ch));
                   while(ch!=-1);     
                   fin.close();     
                   dout.writeUTF("File Received Successfully");                                   
         String Compare(String filename) throws Exception
                        ///dout.writeUTF("entering compare");
                        String dateTempString=new String();
                        Date dateValue=new Date();
                        SimpleDateFormat formatter = new SimpleDateFormat ("hhmmss");
                        dateTempString = formatter.format(dateValue);
                        File dir1 = new File("C:\\FTPnew");
                        boolean success2 = dir1.mkdir();
                        if (!success2) {
                             // Directory creation failed /Already Exists
                        File dir = new File("C:\\FTPnew\\server");
                        boolean success = dir.mkdir();
                        if (!success) {
                             // Directory creation failed /Already Exists
                        File ftemp=new File(dir,dateTempString + filename);
                        File fnewtemp=new File(dir,"new-enc-"+filename);
                        // Create encrypter/decrypter class
                        DesEncrypter encrypter = new DesEncrypter("My Pass Phrase!");
                        FileOutputStream fout=new FileOutputStream(fnewtemp);     
                        int ch;
                        String temp;
                        do
                        {     temp=din.readUTF();
                             ch=Integer.parseInt(temp);
                             if(ch!=-1)
                                  fout.write(ch);                         
                        }while(ch!=-1);
                        fout.close();
                        //dout.writeUTF("written temp en file");
                        // Decrypt
                    encrypter.decrypt(new FileInputStream(fnewtemp),
                    new FileOutputStream(ftemp));
                        //String Option;
                        dout.writeUTF("Delete");                    
                        System.out.println("File Upload Successfull--Duplicate file with timestamp Created");          
                        boolean success1 = fnewtemp.delete();                    
                        return "hello" ;
         void ReceiveFile() throws Exception
              String ip=din.readUTF();
              System.out.println("\tRequest Coming from Internal IP Address : "+ ip);
              String filename=din.readUTF();
              if(filename.compareTo("File not found")==0)
                   return;
              // Destination directory
       File dir11 = new File("C:\\FTPnew");
                        boolean success22 = dir11.mkdir();
                        if (!success22) {
                             // Directory creation failed /Already Exists
                        File dir = new File("C:\\FTPnew\\server");
                        boolean success21 = dir.mkdir();
                        if (!success21) {
                             // Directory creation failed /Already Exists
              File f=new File(dir ,"enc-"+filename);
              File fe=new File(dir,filename);
              String option;
              if(fe.exists())
                   //dout.writeUTF("File Already Exists");
                   String compvalue = Compare(filename);
                   //dout.writeUTF(compvalue);
                   if(compvalue.compareTo("hello")==0)
                        //dout.writeUTF("Transfer Completed");
                        return;
                   option=din.readUTF();
              else
                   //dout.writeUTF("SendFile");
                    option="Y";
                   if(option.compareTo("Y")==0)
                        // Generate a temporary key.       
            // Create encrypter/decrypter class
             DesEncrypter encrypter = new DesEncrypter("My Pass Phrase!");
                 FileOutputStream fout=new FileOutputStream(f);                    
                        int ch;
                        String temp;
                        do
                        {     temp=din.readUTF();
                             ch=Integer.parseInt(temp);
                             if(ch!=-1)
                                  fout.write(ch);                         
                        }while(ch!=-1);
                        fout.close();                    
                        // Decrypt
                    encrypter.decrypt(new FileInputStream(f),
                    new FileOutputStream(fe));          
                        boolean success2 = f.delete();
                        dout.writeUTF("Delete");
                        System.out.println("File Upload Successfull");                    
                   else
                        return;
         public void run()
              while(true)
                   try
                   String Command=din.readUTF();
                   if(Command.compareTo("SEND")==0)
                        System.out.println("\tSEND Command Received ...");     
                        ReceiveFile();
                        continue;
                   catch(Exception ex)
                        //System.out.println("\tClient Terminated Abnormally ...........");
                        continue;

    Please note that this is not an FTP client and server. FTP is defined by a standard IETF protocol and this isn't it.
    Then, move the following lines:
    din=new DataInputStream(ClientSoc.getInputStream());
    dout=new DataOutputStream(ClientSoc.getOutputStream());
    System.out.println("FTP Client Connected ...");
    System.out.println("External IP of Client ..." + ClientSoc.getInetAddress());
    //System.out.println("FTP Client Connected ..."+ClientSoc.getRemoteSocketAddress());from the constructor into the run() method. i.e. don't do anything with the socket in the thread which handles the accept().

  • Socket based application - Performance Issues - Suggestions Needed

    Hi All,
    We have an application which basically has been developed using core java. Here is a high level information about the application:
    a) It opens a serversocket which allows clients to connect to it.
    b) For every new client connection, a separate thread is created and this thread deals with requests from clients, processing the data and replying back to clients.
    c) Each socket is polled continuously and sockettimeout is 2 seconds. If there is a timeout, we handle the situation and socket is again read. So basically sockets is read every 2 seconds. If number of timeouts reaches a configurable value, we close the connection and thread is dropped as well.
    d) In production, three instances of this application are running with the help of a cisco load balancer. It is there for last 5 years.
    However there has always been some minor performance isssues and we have sorted them out using different types of garbage collectors, by introducing hardware load balancers, upgrading the code for new Java versions. It is currently running on 1.4.2.
    However there has always been some performance issues and today while googling over internet I came across following on the bea website which says that core java sockets are not as efficients as native API. BEA has implemented its own APIs for weblogic. My queries are:
    a) Are there any better Java Socket/network API (for solairs, I know Java is plateform independenet but there could be lib which also using native libs) which are much more efficient than Core Java.
    b) We are getting the InputStream/OutputStream and creating objects of DataInputStream/DataOutputStream to read the data 'Byte-By-Byte'. Each byte can have different information thats why it is required. Are there any better way of getting info than what we are currently doing.
    c) As I mentioned, we are continously polling the socket for read operation with a timeout value of 2 seconds. What is the better among the following from performance point of view: (1) Frequent read operation with a lesser timeout value or (2) Less Frequent read operations with larger timeout value. (3) Any better idea??
    Please suggest few things or pointers which I could do to improve the performance of the applcations. Many thanks.
    Thanks,Akhil
    From BEA website:-
    "Although the pure-Java implementation of socket reader threads is a reliable and portable method of peer-to-peer communication, it does not provide the best performance for heavy-duty socket usage in a WebLogic Server cluster. With pure-Java socket readers, threads must actively poll all opened sockets to determine if they contain data to read. In other words, socket reader threads are always "busy" polling sockets, even if the sockets have no data to read. This unnecessary overhead can reduce performance."

    My recommendations:
    - Always use a BufferedInputStream and BufferedOutputStream around the socket streams
    - Increase the socket send and receive buffers to at least 32k if you are on a Windows platform where the default is a ridiculous 8k, which hasn't been enough for about 15 years.
    - Your 2-second timeout is far too short. Increase it to at least 10 seconds.
    - Your strategy of counting up to N short timeouts of S seconds each is completely pointless. Change it to one single timeout of N*S seconds. There is nothing to be gained by the complication you have introduced to this.

  • Not sure if thread is dying

    I have a small chat application passing sockets to seperate threads. The application is set to be a daemon thread so I can close the application that launches it.
    I added small checks throughout the application to see the number of active threads.
    There are two things happenning that I don't understand:
    1. When I first start the application there are always 61 (including newly created daemon) threads running. I assume these are necessary background threads running in the servlet container (Tomcat 5) and the JVM.
    2. When I log in with one client (creating a new socket and therefore new thread on the server's end) the thread count goes to 62. As I log in with other clients the thread count increases accordingly. The strange thing is that when I exit the client application therefore ending the run() method of that thread the first client to exit always seems to have its thread stay alive. By that I mean if I add 3 clients taking the thread count from 61 to 64, then close one client the thread count stays at 64. But then if I close another client then the thread count goes down to 63. The other strange thing is that if I close all clients the thread count remains at 62 (instead of 61 where it should be) and if I then log in another client the thread count remains at 62 but increases with every new client after that. It seems that the first client thread stays active and somehow new sockets can just replace that thread. Since none of the code is different if it's the first socket or the 20th....how can this first one not die and then even get replaced.
    Sorry for the long description....I really am not that well versed in threads. If anyone could shine some light on this problem (or even offer a suggestion as how to better monitor whether the threads are dying or not) I would really appreciate it. Thanks in advance.

    You should experiment/test a little more. Dig around until you can find out what's going on. It's not hard.
    For example, try naming all of your threads. This will allow you to see which threads are yours and which belong to the system. Then, print out the names of only the threads you created, from time to time. You might do this by matching on the name, or perhaps by assigning all of your threads to a single thread group. You also might want to print a message when your thread terminates (that is, at the very bottom of its run() method), for each thread.
    By the way, jconsole is a very useful JVM monitoring tool. It allows you to connect to your application and see which threads are running and what they are doing (among other things). It comes with the Sun JDK.
    Jim

  • Java Server Threading Problems

    Cross-posted at: http://www.java-forums.org/networking/41574-server-threading-confusion.html with no answers as of this edit.
    I'm very new to networking in java, and it's been a few months since I last did any major programming. I decided to try out networking, and I'm beginning to get a feel for it, but I've jumped in to trying to make a server for a multiplayer game, and I've gotten a bit stuck about how to do it, specifically on how to use threads to take care of my clients, and still be able to keep track of the threads so I can have the server send out info to them about where characters are, when the threads should close because someone wants to log out, etc.
    If anyone could help me out that would be awesome :D
    Here's some code:
    import java.net.*;
    import java.io.*;
    public class GameThread extends Thread // this is the actual thread class I made
      public Socket socket;
      public DataInputStream in;
      public DataOutputStream out; // a socket and two I/O streams for sending ints
      public GameThread(Socket socket) // typical constructor for getting socket
        try
          this.socket = socket;
          in = new DataInputStream(socket.getInputStream());
          out = new DataOutputStream(socket.getOutputStream());
        catch(Exception e)
          e.printStackTrace();
      public Socket getSocket() // I don't believe this is ever used. Ignore it.
        return socket;
      public void print() // Used to make sure the thread is active/knows about the socket
        System.out.println("GameThread says: " + socket);
      public void run()
        while(true)
    }Here's the class I use to manage the threads, or, at least, where I attempt to do so.
    import java.io.*;
    import java.util.ArrayList;
    import java.net.*;
    public class Threader
      public ArrayList clients;
      public ArrayList<GameThread> threads; // GameThread is the thread class above
      public Threader()
        threads = new ArrayList<GameThread>(); //constructor for this arraylist
      public void updateClientCount(ArrayList<Socket> clients) // this method works
        this.clients = clients; // it's not the problem.
      public void openThreads() //Here's probably where problems begin
        if(clients.size() > threads.size()) // this is to make the threads arraylist
          int f = clients.size()-threads.size();//equal length compared to clients arraylist
          while(f > 1)
         threads.add(null);
         f--;
        if(clients.size() < threads.size()) //same as above, just if threads is bigger
          threads.subList(clients.size(),(threads.size()-1)).clear();
        for(int h=0;h<clients.size();h++) //Here: for each client spot
          if(threads.get(h) == null) //Threads is tested in that spot to see if there's
          {              // A thread there
         GameThread gt = new GameThread((Socket)clients.get(h));
         threads.add(gt); //and if there isn't then it makes one
         gt.start(); // and starts it, but I guess this isn't happening as I want
          } // it to because in the method below none of the GameThreads print socket info
      public void print() //used to make sure the Threader/GameThread(s) is getting the info
        for(int y = 0;y<clients.size();y++)
          System.out.println("Threader says: " + clients.get(y));
        for(int x = 0;x<threads.size();x++)
          threads.get(x).print();
    }If anyone could help me find what is going on, or maybe (probably) I'm going about making a server wrong (I have another class with a serversocket and all, but I don't believe there are any bugs in it so it isn't included in here), so if I could get help that would be awesome.
    Thanks guys!
    Edited by: 848780 on Mar 30, 2011 8:55 PM
    Edited by: 848780 on Mar 30, 2011 11:55 PM

    Your thread management is back to front. All you need is a new thread per client, started every time you accept a new Socket. When you do that, if you want to manage them, enter the new thread into a collection, and when it exits remove it. But you normally don't need to keep track of client threads. You may want to keep track of client Sockets, in which case you should maintain a collection of Sockets on the same basis.

  • Two sockets in a single server

    May I open two sockets with different listening port numbers in a single server? For each socket, the way to deal with the inputstream and outputstream is different. May the thread be like this:
    public class twoSocketServer implements Runnable {
    public twoSocketServer() {
    try{
    SSLServerSocketFactory fact = SSLServerSocketFactory.getInstance(rand, selfPrivateKey, selfCertificate, trustEngine, null);
    serverSocket1 = (SSLServerSocket) fact.createServerSocket(ListeningPort1);
    serverSocket1.setNeedClientAuth(false);
    serverSocket2 = (SSLServerSocket) fact.createServerSocket(ListeningPort2);
    serverSocket2.setNeedClientAuth(false);
    } catch {...}
    public void run()
    while(true)
    try
    SSLSocket socket1 = (SSLSocket) serverSocket1.accept();
    new handler1(socket1).start();
    SSLSocket socket2 = (SSLSocket) serverSocket2.accept();
    new handler2(socket2).start();
    } catch {...}
    class handler1 extends Thread {...}
    class handler2 extends Thread {...}
    Is there something wrong with this idea? If yes, how can I correct it? Thanks.

    This is better :
    import java.awt.*;
    import javax.swing.*;
    import java.awt.event.*;
    import java.util.*;
    import java.io.*;
    import java.net.*;
    public class MultSrv extends JFrame
         JTextArea   panel   = new JTextArea();
         JScrollPane sbr     = new JScrollPane(panel);
         Vector      sockets = new Vector();
         Vector      servers = new Vector();
    public MultSrv() 
         super();
         SocServer ss1 = new SocServer(this,4444);
         if (ss1.servS != null) ss1.start();
              else               System.out.println("err");
         SocServer ss2 = new SocServer(this,4445);
         if (ss2.servS != null) ss2.start();
              else               System.out.println("err");
         SocServer ss3 = new SocServer(this,4446);
         if (ss3.servS != null) ss3.start();
              else               System.out.println("err");
         try
              InetAddress inet = InetAddress.getLocalHost();
              setTitle("MultServer v1 - "+inet+"  Port=4444/5/6");
         catch(IOException e){}
         setBounds(10,10,400,450);
         setContentPane(sbr);
         panel.setEditable(false);
         addWindowListener(new WindowAdapter()
        {     public void windowClosing(WindowEvent ev)
              {   dispose();
                   System.exit(0);}});
         setVisible(true);
         javax.swing.Timer ta = new javax.swing.Timer(2000, new ActionListener()
              public void actionPerformed(ActionEvent e)
                   panel.setText("");
                   for (int i = 0; i < sockets.size(); i++)
                        SocServer ss = (SocServer)sockets.get(i);
                        if (ss.servS == null) panel.append(""+ss.port +ss.err);
                             else              panel.append(""+ss.port +" Active");
                        panel.append("\n");     
                   for (int i = 0; i < servers.size(); i++)
                        Server server = (Server)servers.get(i);
                        panel.append(""+server.clnt.getInetAddress()+" Is serviced");
                   repaint();
         ta.start();     
    public void go(Socket clnt)
         Server server = new Server(clnt);
         servers.add(server);
         server.start();
    //  The ServerSocket
    public class SocServer extends Thread
         ServerSocket servS;
         int          port;
         String       err = "";
         Socket       clnt;
         MultSrv      mserv;
    public SocServer(MultSrv mserv, int port) 
         this.mserv = mserv;
         this.port  = port;
         sockets.add(this);
         try
              servS = new ServerSocket(port);
         catch (IOException e)
              err = e.toString();;
    public void run()
         try
              while (true)
                   clnt = servS.accept();
                   mserv.go(clnt);
         catch (IOException e)
    //  The Server.. one for each client
    public class Server extends Thread
         Socket                clnt = null;
         OutputStream       out  = null;
         InputStream        ins  = null;
    public Server(Socket soc) 
         clnt = soc;
    public void run()
         try
              ins  = clnt.getInputStream();
              out  = clnt.getOutputStream();
              while (true)
         catch (IOException e){}
         try
              ins.close();
              out.close();
              clnt.close();
         catch (IOException e){}
    public static void main (String[] args) 
         new MultSrv();
    }     

  • Thread for a client

    I need some quick help, I am changing a program from using sockets to using RMI. How can I accept a connection from a client to assign to a thread. I don't think I explained it well so here's what I am using currently with sockets. I'm new to Java.
    private ServerSocket server;
    private Socket userA, userB;
    server = new ServerSocket(3012);
    userA = server.accept(); //How do I to do this with RMI (confused)
    userB = server.accept();

    RMI is inherently multi-threaded. If twoi users call a remote function, there will automatically be two threads of activity, more-or-less active at the same time.
    There is no notion of "connection", and no notion of "accept". If you want these, then you have to write your own - perhaps as synchroinzed methods within the remotely-called server code.

Maybe you are looking for

  • Can I use the old Classic mode on a new iMac?

    On my old iMac G5 running OS X 10.3.9, I also had a "Classic" mode that worked with all my old apps. I just bought a newer iMac (10 months old) running OS X version 10.6.6. Can I install Classic on it too? If not, is there some other way that I can r

  • Crashing issues not solved with extensive troubleshooting... Please help!

    Hello community,  I'm still in the process of trying everything to resolve these issues, be it hardware related, software... Or both. Here's an extensive account of the troubles I have been experiencing and maybe someone here who has encountered a si

  • Cut and delete (paste and copy)

    Hello all. I have written a simple Spreadsheet application using the JTable. I had thought i correctly implemented the cut/copy/paste and delete methods as when i selected a range of values, and click cut, the would disapear and paste when i selected

  • How to create Webservice using java

    Hi Experts,       I am very new to Visual composer, can any one of you suggest how to create a webservice using java so that i can use that webservice in Visual Composer application.If it is possible please give me detailed description about it. Rega

  • Pre-owner's contacts in i-pad still there.

    My ipad was owned by another relative before I got it. It has been set up for me---mostly. I still have a problem with the contacts. They are his even though many are also my relatives. How do I change from him in the CONTACTS window where it says "M