Socket  Hangs in KnockKnock

Lots of research on forums, FAQs, tutorials and I'm still getting slammed by Java Socket applications. Ultimately I am trying to connect to a Skype instance to record but can't get the published examples to work. I'm running XP.
I went back to the Java tutorials and tried EchoClient and KnockKnockServer. Each compiles but EchoClient (modified to use "localhost" and either port 7 or 4444) gives a "Connection refused: connect" error and KnockKnock hangs on the socket.accept statement. I have turned off my windows firewall, listed the programs as exceptions for the firewall. Doesn't seem to matter. I checked Norton Antivirus and can't find any settings that might be a problem.
I downloaded thread dumps for the KnockKnock. The CompilerThread0 and SignalDispatcher were "waiting on condition", Finalizer is waiting on ReferenceQueue$Lock and ReferenceHandler is waiting on a Reference$Lock
One other datapoint. In NetBeans I tried to "attach a debugger.." SocketAttach;localhost;4444 or 4447 or 4449. The Output- Debugger Console says: "Attaching to localhost: 4444. Connection refused."
Writing threaded java using SQL queries was a lot easier than this. Is there something simple I'm doing wrong?
Thanks

EchoClient (modified to use "localhost" and either port 7 or 4444) gives a "Connection refused: connect" errorThat means nothing is listening at the host:port you specified. The host has to be the name of the host the server is running in and the port needs to be the port it is listening at.
and KnockKnock hangs on the socket.accept statement.That means that nobody has tried to connect to the correct host:port.
Moral: get the port correct in the server, and the host and port correct in the client.
You probably think you've already done that, but I'm afraid the evidence is against you ...

Similar Messages

  • Server socket Hangs

    Hi,I am using the server socket in Java to listen on a port on a computer..
    I am using the windows platform
    I use ms vj++6.0
    I am facing a peculiar problem.
    about once in 10 messages received by my server socket,
    The server socket hangs .
    Hangs means it stops responding to the incoming message & so my application
    is unable to take any action.
    I used a port scanner & found that my server port is in a "close_wait"
    state.
    Can someone tell me the reason for this.
    is it a problem with my server or can the client that sends the message be
    also responsible for this type of an error.
    Heres the code for my server
    public server()
    try
    server = new ServerSocket(2156);
    serverthread = new Thread(this);
    serverthread.start();
    catch(Exception e)
    System.out.println("Cannot Start Thread" + e);
    public synchronized void run()
    try
    while(true)
    String line;
    System.out.println("listening for the client");
    fromclient = server.accept();
    System.out.println("client has responded");
    InputStreamReader isr = new
    InputStreamReader(fromclient.getInputStream());
    BufferedReader instream = new BufferedReader(isr);
    PrintWriter ostream = new PrintWriter(new
    BufferedOutputStream(fromclient.getOutputStream()));
    System.out.println("talking to the client\n");
    ostream.println("Hye Client");
    ostream.println("Bye");
    ostream.flush();
    System.out.println("listening to the client \n");
    String temp;
    int count=0;
    String ip="";
    while((line=instream.readLine())!=null)
    System.out.println(line+"\n");
    if (line.equals("Bye"))
    break;
    if (line.equals(""))
    continue;
    else
    System.out.println(line+"\n"); /*Print the line that has come in the
    socket*/
    ostream.close();
    fromclient.close();
    catch(Exception e)
    System.out.println("Cannot listen to the client" + e);
    I hope somebody can help me out .
    Thanx in advance
    Regards
    Sanket Gupta

    You don't seem to properly close the server socket any where. Here why don't you look at this skeleton. This may help you.
    import java.net.*;
    import java.io.*;
    import java.util.*;
    public class server
         static boolean listen = true;
         public static void main(String args[])
              try
                   ServerSocket ss = new ServerSocket(2156);
                   do
                        new serverThread(ss.accept()).start();
                   while(listen);
                   ss.close();
              catch(IOException e)
                   System.err.println(e.getMessage());
         public static void shutdown()
              listen = false;
    class serverThread extends Thread
         private Socket client;
         private String input;
         private BufferedReader in;
         private PrintWriter out;
         public serverThread(Socket c)
              client = c;
         public void run()
            try
              in = new BufferedReader(new InputStreamReader(client.getInputStream()));
              out = new PrintWriter(client.getOutputStream(),true);
              input = in.readLine();
              if(input.equals("Hello"))
                   out.println("How are you doing?");
              else if(input.equals("shutdown!"))
                   server.shutdown();
              else
                   out.println("Bad Request!");
              in.close();
              out.close();
              client.close();
            catch(IOException e)
                 System.err.println(e.getMessage());
    }

  • Close socket hangs in SunOS5.6

    The close() function is hanging when I attempt to close a socket. I have a small multi-threaded program, which I will attach below, which replicates the problem. Basically, the program creates a thread which listens for a datagram from a socket using the recvfrom() function. When the main thread attempts to close the socket being listened to, the close() function never returns. My guess is the recvfrom() function is doing some kind of blocking and somehow needs to be told to quit waiting. However, I'm not sure how one does this. Any ideas are greatly appreciated.
    Sun tech. support recommended installing some patches we are missing. While that may ultimately be the solution, I would like to avoid doing so because this would affect multiple products we are developing and many of our customers.
    The related portion of the code is:
    main()
    /* create thread using pthread_create() */
    while (1) {
    fgets(c, sizeof(c), stdin);
    if (c[0] == '\n')
    break;
    fprintf(stderr, "Closing socket\n");
    close(sockfd);
    exit(0);
    void wait_awhile(void) {
    char buff[MAXLINE];
    int n;
    fprintf(stderr, "\nIN THREAD: prior to socket call\n");
    sockfd = socket(AF_INET, SOCK_DGRAM, 0);
    if (sockfd < 0) {
    fprintf(stderr, "could not create socket\n");
    exit(0);
    /* Get the server's socket address */
    bzero((struct sockaddr_in *)&servaddr, sizeof(servaddr));
    clientaddr_len = sizeof(struct sockaddr_in);
    servaddr.sin_family = AF_INET;
    servaddr.sin_port = htons(3500);
    servaddr.sin_addr.s_addr = inet_addr(ip_address);
    /* Bind it to the port */
    fprintf(stderr, "IN THREAD: Binding socket\n");
    if (bind(sockfd, (SA *) &servaddr, sizeof(servaddr)) < 0)
    close(sockfd);
    fprintf(stderr, "could not bind socket\n");
    exit(0);
    while (1)
    fprintf(stderr, "IN THREAD: Waiting for datagram\n");
    if ( (n = recvfrom(sockfd, buff, MAXLINE, 0, (SA *)&clientaddr, &clientaddr_len)) < 0)
    close(sockfd);
    }

    "Shirley" <[email protected]> wrote:
    >
    "Khalid" <[email protected]> wrote:
    We seem to have close wait problem in extreme load where apache/weblogic
    hold the
    tread so the socket cannot be closed. Does anyone know how to fix this
    problem.
    It seems like after in runs out of thread the server crashes.
    Have you fixed this problem you were facing ,because we are facing exactly
    the
    same problem.Did you find any solution .If so please do let us know
    Cheers
    Shirley RemediosWe had the same problem and reduced the number of sockets in this state by reducing
    the time to wait before closing the sockets. On Solaris we set 'tcp_time_wait_interval'
    to 30000 (30 seconds) on the web and app servers.

  • Sockets hang using PrintWriter and BufferedReader

    Solaris 2.7, and Java 1.2.2
    My thread is passed a new socket = s. I then assign:
    InputStreamReader isr = new InputStreamReader(s.getInputStream());
    BufferedReader br = new BufferedReader(isr);
    PrintWriter pw = new PrintWriter(s.getOutputStream());
    The client program then sends records. If each record has only a "\r" then
    the program fails. If the client sends a "\n" or "\r\n" then the program
    works fine.
    The documentation for BufferedReader states that it looks for a "\r" or a
    "\n" or a "\r\n".
    I don't get any indication that there is a problem other than the hang.
    Upon Connect...
    Server> send("0000\n")
    client> recv("0000\n")
    client> send("0001\r")
    Server> recv("0001")
    Server> send("0002\n")
    client> recv -- nothing...
    Server> recv paused...
    I have run truss on this process and it shows that nothing is sent on the last server send above. When the client gives up (e.g. timeout) the the send completes as truss sees it.
    Is this a bug in 1.2.2. or a documentation error?

    use flush()!!

  • StreamReader from TCP Socket Hanging...I think

    Hello all, and thank you in advance for any and all help. Allow me to start out by apologizing as I have only been programming Java for about 3 days now, however I am a bit stuck and have spent about 5 hours trying to figure out what could be my problem here.
    I have written an app that connects to a usenet server and pulls that list of groups from the server, however it seems as if the BufferedReader doesn't have a large enough buffer to hold the response from ther server. I can save the output of the log from putty during the LIST command and I recieve 108897 lines of text (about 5 mb in total) however in my Java app it gets to line #108598 and hangs. I have tried messing with the buffer sizes of the StreamReader as well as the Socket, and if I try to set the buffer size of the BufferedReader {+bufferedreader(stream,int)}+ It won't compile.
    Well here is the code, and again, i apologize if this is sloppy/not correct coding practices. I am new at Java.
        private void jButton1MouseClicked(java.awt.event.MouseEvent evt) {                                     
        try {
            String data = "";
            Socket skt = new Socket("127.0.0.1", 119);
            BufferedReader in = new BufferedReader(new InputStreamReader(skt.getInputStream()));
            while (!in.ready()){}
            data = in.readLine();
            //log.append(data.toString() + "\n");
            Scanner sc = new Scanner(data);
            int command = sc.nextInt();
            if (command == 200) {
                log.append("Connection established to" + sc.nextLine() + "\n");
                log.append("Sending Log-in Credentials \n");
                PrintWriter out = new PrintWriter(skt.getOutputStream(), true);
                out.println("AUTHINFO USER " + txtUser.getText());
                while (!in.ready()){}
                data = in.readLine();
                sc = new Scanner(data);
                command = sc.nextInt();
                if (command == 381) {
                    out.println("AUTHINFO PASS " + txtPass.getText());
                while (!in.ready()){}
                data = in.readLine();
                sc = new Scanner(data);
                command = sc.nextInt();
                if (command == 281) {
                    log.append("Successfully logged in \n");
                    log.append("Getting list of active groups \n");
                    out.println("list");
                    while (!in.ready()){}
                    data=in.readLine();
                    Writer output = null;
                    File outfile = new File("c:/data/groups.txt");
                    output = new BufferedWriter(new FileWriter(outfile));
                    output.write(data + "\n");
                    out.println("Date");
                    int i = 0;
                    while ( i != 108897) {
                        data = in.readLine();
                        output.write(data + "\n");
                        i += 1;
        catch (Exception ex) {
            System.out.print(ex.getMessage());

    while (!in.ready()){}Remove that. It's just burning CPU. The following readLine() will block until the line arrives.
    while (!in.ready()){}Ditto.
    while (!in.ready()){}Ditto.
    while (!in.ready()){}Ditto.
    while ( i != 108897) {
    data = in.readLine();At this point (and every other readLine()) you must check for data == null, which is EOS, and break, and close the stream, if you get it.

  • Write to socket hange the process

    Hi, my program uses sockets. All is fine, but when the other side suddenly shut downs, my process
    stays hung into the write system call. According to pStack, my process is also stuck on the
    close system call (Since it noticed that the other side was shut down). What happeded ? did the process entered some deadlock because trying to close a socket that is trying to write to it??
    I can't even receive any terminating signals, when normally I receive them with no problem.
    Please help!!!

    This is what I get, what do you get:
    java -server Loopback1000000 messages in 3004 ms
    1000000 messages in 2752 ms
    1000000 messages in 2706 ms
    1000000 messages in 2728 ms
    import java.io.*;
    import java.net.*;
    public class Loopback
        static final int PORT = 6666;
        public static void main(String args[])
         throws Exception
         new Listener().start();
         Socket socket = new Socket("localhost", PORT);
         DataOutputStream out = new DataOutputStream(new BufferedOutputStream(socket.getOutputStream()));
         int count = 0;
         long start_time = System.currentTimeMillis();
         while (true) {
             out.writeBytes("hello world");
             out.flush();
             if (++count % 1000000 == 0) {
              long now = System.currentTimeMillis();
              System.out.println("1000000 messages in " + (now - start_time) + " ms");
              start_time = now;
        static class Listener
         extends Thread
         ServerSocket server_socket;
         Listener()
             throws IOException
             server_socket = new ServerSocket(PORT);
         public void run()
             try {
              while (true) {
                  Socket socket = server_socket.accept();
                  InputStream in = socket.getInputStream();
                  byte buf[] = new byte[8192];
                  while (true) {
                   if (in.read(buf) == -1)
                       break;
                  in.close();
                  socket.close();
             } catch (IOException e) {
              System.out.println("error in listener: " + e);
    }

  • Sockets hanging ?!?

    Hi.
    I am experiencing a strange problem.
    If I send a message to the following piece of code I get it only once unil I do not restart the sending program again. How can I keep receiving messages keeping this functionality?
    10x in advance
    try {                          
    InetAddress serverInet = InetAddress.getLocalHost();
    ServerSocket = new ServerSocket(hostPort,50,serverInet);
    } catch (IOException e) {
    System.err.println("Could not listen on port: "+hostPort);
    System.exit(1);
    Socket clientSocket = null;
    while (true) {
    try
         try {
         clientSocket = serverSocket.accept();
         } catch (IOException e) {
         System.err.println("Accept failed");
              System.exit(1);
    // code doing this
    open new Socket // tcp connection
    read/write from it
    close it
    } catch (Exception e) {
         e.printStackTrace();
    }

    You must spawn a new thread in order to accomplish concurrent processing of client sockets. This is if you're using a version of the platform pre-j2sdk1.4.0
    With this latest version, there is the notion the select() functionality. This promises improved performance over the thread-per-client model that has been required until now.
    Check out the latest JDK(1.4.0), specifically, the java.nio.* classes.
    Hope this helps,
    - Phil

  • In AIR 3.x, a socket write()+flush() on a client will hang app if peer adverts TCP ZERO WINDOW

    In AIR 3.x, a socket write() + flush() on a client will hang (and freeze the entire app) if the socket peer advertises a ZERO TCP Window, i.e. no space available in peer receiver's socket buffer.
    AIR on Windows insists that the developer flush() the socket in order to write (any data at all).  When the peer (receiver) advertises a 0 byte tcp window, the client flush() call can sometimes take 10 seconds (i.e. 10000 milliseconds), whereas normally it should take 10 to 50 milliseconds.
    Additionally, AIR stayed in hung position.  Since the socket had TCP KEEPALIVE option enabled (at the server), the socket stayed open.  I let it stay hung overnight.  The next day when I rebooted the server, the socket got closed and finally the AIR program "RETURNED FROM the sock.flush()" call.  A timestamp before and after the call to flush() showed that the flush() call was in hung state for 56472475 milliseconds, i.e. 15.7 hours!  After it returned from the flush() call the AIR app was responsive and seemed to work properly.  Thus proving that it was indeed stuck (or blocked) on the flush() call for 15 hours trying to drain the data to a socket with zero tcp window condition.
    A tcp zero window condition on 1 socket hanging an entire app sounds concerning.
    Solution Suggestions:
    (1) What is needed is for the OutputProgress event to include a field for 'bytes that can be written safely without blocking on the socket', i.e. 'space available in underlying platform socket buffer' which would account for the socket send buffer size.
    (2) An alternative solution would be for AIR to provide a write-timeout setsockopt (or a writeTimeout() method on the socket), and return flush with an error (or EWOULDBLOCK), and call the OUTPUTPROG event only when there is enough space available.
    If there are any other workarounds, please let me know.
    Thank you.

    Question:  Does Adobe AIR expose the getsockopt() and setsockopt() calls on a socket?  It would be useful to apps to tune the io buffer sizes.
    Additional Details:
    RTT = 100+ milliseconds
    TCP Window Scaling enabled
    Secure Socket
    Hard to reproduce with plain TCP socket, but occurs without fail with SecureSocket.  Not knowing the underlying code base, am wondering if it is because the SSL encryption overhead (bytes) throws off the buffer available size compution in secure_sock.flush() .
    Thanks.

  • Socket read not returns all bytes

    Hi all,
    we developed an java application which creates customer orders over the internet. The java application sends commands to our erp system, which creates the order. The communication between these system is realised with sockets. On my local pc everything works fine. But on our live system (sun - solaris) we become some problems. For the first entry send over the socket it works. But if another entry is added we got a problem. After sending ovber the socket the erp system creates the order and returns the checked data. The data returned are read as followed:
    protected void readFromSocket(byte[] buffer, int offset, int length)
    throws IOException {
    Arrays.fill(buffer, (byte) 0xee);
    int bytesRead = 0;
    while (bytesRead != length) {
    bytesRead = getIn().read(buffer, offset + bytesRead, length - bytesRead);
    While reading the second entry from the stream, it hangs. The socket does not return the full number of bytes we recommended.
    I will be thankfull for any idea.
    Thanks

    I would suspect that you have an infinite loop because you're not performing the correct logic, not that the socket hangs. Try putting a System.out.println("I read another " + bytesRead + " bytes from the socket...") statement after the read and see if it keeps printing something over and over.

  • JSP+RMI = socket leak (with tomcat 5)

    Tried this in the RMI forum, no answer, so let's try here...
    When I use RMI from a JSP servlet, I have a "socket leak" problem. When I create an RMI unicast remote object, the RMI library (of course) opens up a server/listening socket. In a normal application, I can unbind the remote object, but then the next object I create will re-use the same server socket, so the server socket never closes, but only one is ever created, so it's not a big deal.
    Now for the problem: When I use the Tomcat manager to unload my webapp, the socket is still there. Sure, fine. But then when I reload the webapp, instead of re-using the same server socket, a new one is created! Furthermore, if I try to use explicit port numbers to force the server socket to be reused, I get "port already in use" errors. It seems that somehow tomcat won't let RMI recycle its entry points in between webapp restarts. Does anybody know how I can either:
    a) Get RMI to re-use the same ports
    b) Get RMI to completely shut down its ports when the webapp is unloaded (this would be even better)
    Thanks. It's irritating to see 10 open but unused server sockets on my system if I have to restart the webapp.

    Ah, I left out something: I construct the RMI object a servlet context listener in the contextInitialized() call, and I call UnicastRemoteObject.unexportObject() in the contextDestroyed() call. I added log messages, I am definitely correctly unbinding the object. The problem isn't that it is failing to be unbound - the problem is that the RMI system is refusing to reuse the same port after it is unbound. After unbinding, the port is still open, but it is never reused, each time I re-instantiate the remote object, it is making a new server socket and leaving the old one sitting open.
    As for why I'm doing this, it is a bit like a homegrown EJB, but just so small that this was the simplest way. I have a largish non-web based application, then I have a few JSP pages that do database queries to provide information to browsers. The JSP pages are not at all central to the application though, and just show some database info. The JSP system caches some SQL data, and I use RMI to tell JSP when to flush cached data due to database changes. It's all very simple, and it works fantastic, except for the issue that every time I reload the webapp I leave these server sockets hanging open. Even that is just an irritation, I don't reload much except when I'm testing, but it's a big enough irritation that I would really like to fix it.

  • Kernel panic, then x11.app won't launch.

    I had a kernel panic a hour or two ago while doing a bunch of stuff (compiling pkgsrc bootstrap, running virtual pc, and surfing w/firefox), and now X11.app won't launch. The only error messages I can find are in the console log:
    XFree86 Version 4.4.0 / X Window System
    (protocol Version 11, revision 0, vendor release 6600)
    _XSERVTransmkdir: Owner of /tmp/.X11-unix should be set to root
    [DRI] screen 0 installation complete
    Screen 0 added: 1024x768 @ (0,0)
    Could not init font path element /usr/X11R6/lib/X11/fonts/CID/, removing from list!
    bind: Address already in use
    X connection to .0 broken (explicit kill or server shutdown).
    Quitting XDarwin...
    Any thoughts? This is right after a clean reboot, too...
    powerbook 12" Mac OS X (10.4.7)

    Feh, of course right after posting this, I figured it out.
    I had an ssh-agent socket hanging around, apparently that did it.
    +j

  • Problem in Mail deletion in POP3

    Hi
    I am using Pop3.
    I opened folder using
    folder.open (Folder.READ_WRITE);
    setting flag for deletion
    mimeMessages.setFlag (Flags.Flag.DELETED, true);
    then in finally block closing the folder
    if (mailbox.isConnected ()) {
    if(folder != null && folder.isOpen()) {
    try {
    folder.close (true);
    sometimes it is not deleting the messages.
    Please suggest something.
    Thanks
    Atal

    I am sorry but what do u mean by this? can u please explain in detail.
    actually most of times it works fine but in few cases mail deletion is failing.
    In my code: after folder.close (true); I just take a dump that comes successfully.
    The MailBox folder has been closed after deleting the ToBeDeleted Mails, if any, by folder.close method.
    MessageId of 1 th message which has been marked for Deletion : 1150475083.23686.prod-util-1.aspdeploy.com,S=57857
    MessageId of 2 th message which has been marked for Deletion : 1150475117.23813.prod-util-1.aspdeploy.com,S=6808
    MessageId of 3 th message which has been marked for Deletion : 1150475120.23818.prod-util-1.aspdeploy.com,S=9425
    MessageId of 4 th message which has been marked for Deletion : 1150475140.23852.prod-util-1.aspdeploy.com,S=6121
    these 4 messages were marked for deletion.
    then close called. after
    The MailBox folder has been closed after deleting the ToBeDeleted Mails, if any, by folder.close method.
    message, it again tries to retrieve the folder with messages
    Retrieving messages for mailbox ..
    MessageId of the: 1 th message is 1150475083.23686.prod-util-1.aspdeploy.com,S=57857
    MessageId of the: 2 th message is 1150475117.23813.prod-util-1.aspdeploy.com,S=6808
    MessageId of the: 3 th message is 1150475120.23818.prod-util-1.aspdeploy.com,S=9425
    MessageId of the: 4 th message is 1150475140.23852.prod-util-1.aspdeploy.com,S=6121
    MessageId of the: 5 th message is 1150475338.13255.prod-util-2.aspdeploy.com,S=7458
    MessageId of the: 6 th message is 1150475387.13339.prod-util-2.aspdeploy.com,S=6394
    MessageId of the: 7 th message is 1150475393.13357.prod-util-2.aspdeploy.com,S=59238
    MessageId of the: 8 th message is 1150475553.13615.prod-util-2.aspdeploy.com,S=86236
    first 4 messages are same which were not deleted.
    I have just attached the code. If you want to have a look then plz.
    thanks
    atal
    package com.deploy.email;
    import com.baltimore.jpkiplus.vaults.Vault;
    import com.baltimore.jpkiplus.x509.JCRYPTO_X509Certificate;
    import com.baltimore.jsmt.smime.JSMTException;
    import com.baltimore.jsmt.smime.SMIMEv2;
    import com.deploy.email.api.EmailException;
    import com.deploy.email.api.InitException;
    import com.deploy.email.api.ReceivedMessage;
    import com.deploy.email.config.LogicalMailboxConfiguration;
    import com.deploy.email.config.MailConfiguration;
    import com.deploy.email.config.PhysicalMailboxConfiguration;
    import com.deploy.email.util.SecureEmailHelper;
    import com.sun.mail.pop3.POP3Folder;
    import java.io.ByteArrayInputStream;
    import java.io.ByteArrayOutputStream;
    import java.io.IOException;
    import java.io.InputStream;
    import java.io.InputStreamReader;
    import java.io.BufferedReader;
    import java.security.MessageDigest;
    import java.security.NoSuchAlgorithmException;
    import java.util.ArrayList;
    import java.util.Enumeration;
    import java.util.HashMap;
    import java.util.List;
    import java.util.Vector;
    import javax.mail.Address;
    import javax.mail.AuthenticationFailedException;
    import javax.mail.Flags;
    import javax.mail.Folder;
    import javax.mail.Message;
    import javax.mail.MessagingException;
    import javax.mail.Multipart;
    import javax.mail.Part;
    import javax.mail.Store;
    import javax.mail.UIDFolder;
    import javax.mail.internet.InternetAddress;
    import javax.mail.internet.MimeMessage;
    import javax.naming.NamingException;
    import org.apache.log4j.Logger;
    * This class spawns a thread for each mailbox and pulls messages from those mailboxes at a specified interval.
    * Use start to initialize and stop to end the threads
    * Bug Fixes
    * - 8399 Broke out the mailServer into two separate potential servers; sendMailServer and receiveMailServer
    * This class was updated to reflect the receiveMailServer setting
    * 04/25/03 John Gemski
    * - 10619 Added support for the Lotus Notes Client as per the 3.x fix. Copied logic from 3.x as detailed
    * by Hari in the bug report
    * 08/13/03 John Gemski
    * - Added Email Client Calendaring support - John Gemski 10/21/2003
    * @see com.deploy.email.EmailChannel
    public class RetrieveMail implements Runnable {
    /** Used to tell the threads when to stop */
    private static boolean keepRunning=true;
    //anish For nationwide
    private int maximumsizeofinbox=-1;
    /** The messages on the mail server that have been pulled but not deleted */
    private HashMap messagesOnServer;
    /** These are the mailbox types. Will only be one here for the Azetra impl */
    private static List logicalMailboxes;
    /** The list of running threads. Need to be tracked so they can be interrupted upon stop */
    private static ArrayList receiveThreads;
    /** A reference to the EmailChannel object, which may contain updated information. */
    private static EmailChannel emailChannel = EmailChannel.getInstance();
    private static Logger log = Logger.getLogger(EmailChannel.LOGGER_MODULE_NAME);
    // Thread variables
    /** the configuration for the physical mailbox from which the emails are being pulled. */
    private PhysicalMailboxConfiguration tPhysicalMailbox;
    /** the logical type (OLJB, ScanWorld, Task Response, Resume) that the physical mailbox thread is pulling for */
    private String tLogicalType;
    /** JavaMail Store */
    private Store mailbox;
    // Acceptable Protocols to retrieve mail from the mail server.
    public static final int RECEIVE_MAIL_PROTOCOL_POP3 = 0;
    public static final int RECEIVE_MAIL_PROTOCOL_IMAP = 1;
    public static final int NUM_RECEIVE_MAIL_PROTOCOLS = 2;
    public static String [] RECEIVE_MAIL_PROTOCOL_NAME;
    /** Indicates whether or not the Secure Email feature is enabled. */
    private static boolean secureEmailEnabled =false;
    static {
    RECEIVE_MAIL_PROTOCOL_NAME = new String [NUM_RECEIVE_MAIL_PROTOCOLS];
    RECEIVE_MAIL_PROTOCOL_NAME [RECEIVE_MAIL_PROTOCOL_POP3] = "pop3";
    RECEIVE_MAIL_PROTOCOL_NAME [RECEIVE_MAIL_PROTOCOL_IMAP] = "imap";
    // FIX for socket hang issue (FIX PR 14253) while processing the mail
    public static final String SOCKET_READ_ERROR = "No inputstream from datasource";
    /** Constructor for new RetrieveMail thread.
    * @param phys_config the mailbox configuration for a specific physical mailbox (i.e. [email protected])
    * @param logical_type the logical type for this mailbox ("Resumes", "OLJB", "ScanWorld", or "TaskResponse")
    private RetrieveMail(PhysicalMailboxConfiguration phys_config, String logical_type) {
    this.tPhysicalMailbox = phys_config;
    this.tLogicalType = logical_type;
    * Retrieve email messages from a mail server for the particular physical mailbox indicated with the thread
    * @throws EmailException if any fatal error occurs with the retrieval or processing of the incoming emails
    private void retrieveMessages () throws EmailException {
    Vector msgVector = new Vector ();
    Vector deleteMsgVector = new Vector ();
    ReceivedMessage [] recMessages;
    MailConfiguration mailConfig = emailChannel.getMailConfiguration();
    long maxReceivedEmailSize = mailConfig.getMaximumReceiveSize();
    //Anish for Bug 20366 for Nationwide Patch 06
    maximumsizeofinbox = mailConfig.getMaximumsizeofinbox();
    // Synchronize on the mailbox object for the mailbox from which we
    // are going to retrieve messages. We don't want more than one
    // thread connected to a mailbox at a time, but we don't want to
    // prevent multiple different threads from being connected to
    // multiple different mailboxes simultaneously.
    synchronized (mailbox) {
    boolean throwingException = false;
    Folder folder = null;
    try {
    /* Fix for 8399 - use the getReceiveMailServer call instead of the
    * getMailServer call
    // Connect to the server for receiving mail.
    mailbox.connect (mailConfig.getReceiveMailServer(),
    tPhysicalMailbox.getMailboxName(),
    tPhysicalMailbox.getMailboxPassword());
    // We are only interested in the "INBOX" folder.
    folder = mailbox.getFolder ("INBOX");
    // Open with write permissions as well, so we can delete messages from the server
    folder.open (Folder.READ_WRITE);
    // Anish for Bug 20366 for Nationwide Patch 06
    //int numMessages = folder.getMessageCount ();
    int numMessages1 = folder.getMessageCount ();
    int numMessages = 0;
    //log.info("Anish123 " + maximumsizeofinbox);
    if (maximumsizeofinbox < 0)
    numMessages = numMessages1;
    else
              if (numMessages1 > maximumsizeofinbox) {
              numMessages = maximumsizeofinbox;
              //log.info("Anish try 1 " + numMessages1);
              else {
              numMessages = numMessages1;
              //log.info("Anish try 2 " + numMessages);
    //     log.info("Anish try 4 " + numMessages);
    // End by anish
    if (numMessages > 0) { // There are messages to retrieve
    Message [] messagesRaw = folder.getMessages ();
    // We need to cast the messages to MIME message objects so
    // that we can access some MIME message-specific functionality.
    MimeMessage [] mimeMessages = new MimeMessage [numMessages];
    for (int i = 0; i < numMessages; i++) {
    mimeMessages = (MimeMessage) messagesRaw [i];
    // We can only get messages totalling maxReceivedMessageSize bytes.
    // Calculate how many messages we may get and still stay under the limit.
    int numMessagesToRetrieve = 0;
    int i = 0;
    if( maxReceivedEmailSize > 0) {
    int totalSize = 0;
    numMessagesToRetrieve = 0;
    boolean reachedLimit = false;
    while ((i < numMessages) && !reachedLimit) {
    int messageSize = mimeMessages[i].getSize ();
    int newTotalSize = totalSize + messageSize;
    if (newTotalSize > maxReceivedEmailSize) {
    //if this is the first message then break out and process it
    if( i == 0 ) {
    i++;
    totalSize = newTotalSize;
    reachedLimit = true;
    else {
    totalSize = newTotalSize;
    i++;
    numMessagesToRetrieve = i;
    i = 0;
    else {
    numMessagesToRetrieve = mimeMessages.length;
    while( i < numMessagesToRetrieve )
    boolean gotMessage = false;
    String uniqueID = null;
    if( numMessagesToRetrieve > 0 ) {
    // Get the ID for the message
    uniqueID = getUniqueID (mimeMessages[i], folder);
    //By Anurag for Req#2907 to add Debugging Logs start
    log.info("MessageId of the: " + (i+1) + " th message is " + uniqueID);
    //By Anurag for Req#2907 to add Debugging Logs End
    // Check if we have previoiusly retrieved this message.
    Object value = messagesOnServer.get (uniqueID);
    gotMessage = (value != null);
    if (!gotMessage) { // Make sure message is filled in.
    boolean processMessage = true;
    try {
    if(secureEmailEnabled) {
    ByteArrayOutputStream os = new ByteArrayOutputStream();
    mimeMessages[i].writeTo(os);
    InternetAddress[] senders = (InternetAddress[])mimeMessages[i].getFrom();
    InternetAddress[] recipients = (InternetAddress[])mimeMessages[i].getRecipients (Message.RecipientType.TO);
    Exception lastException = null;
    Vault v = null;
    for (int countRecipients = 0; countRecipients < recipients.length; countRecipients++) {
    lastException = null;
    v = null;
    // try to get the recipient's address from the Vault hash table
    log.info("Trying to get Vault for address: " + recipients[countRecipients].getAddress ());
    v = SecureEmailHelper.getVault (recipients[countRecipients].getAddress ());
    // we can't decrypt if we don't have a private key from the vault!
    if (v == null) {
    log.info("The PFX file for the email account: " + recipients[countRecipients].getAddress () + " is not found or invalid. Please correct.");
    lastException = new EmailException(EmailException.REASON_UNKNOWN, "The PFX file for the email account: " + recipients[countRecipients].getAddress () + " is not found or invalid. Please correct.");
    else {
    break;
    // if we came out with all exceptions, throw the last one we received.
    if (lastException != null) {
    log.error(lastException.getMessage(), lastException);
    throw lastException;
    SMIMEv2 smimer = new SMIMEv2(v);
    // Set up input and output streams to read an S/MIME message
    byte[] originalMessageBytes = os.toByteArray();
    String origMessStr = new String(originalMessageBytes);
    // The SMIMEv2 can't handle extra characters.
    // Noticed that messages contained an "+OK", which was causing problems
    // removed the entire line
    if(origMessStr.startsWith("+OK")) {
    int index = origMessStr.indexOf("\n");
    origMessStr = origMessStr.substring(index+1);
    byte[] revMessageStr = origMessStr.getBytes();
    ByteArrayInputStream input_source = new ByteArrayInputStream(revMessageStr);
    ByteArrayOutputStream output_sink = null;
    boolean smimeRecognized=true;
    boolean wasSigned=false;
    boolean wasEncrypted=false;
    // Making changes to reflect Baltimore's suggestion about layers
    ByteArrayInputStream newMessage = null;
    boolean done=false;
    // According to Baltimore, there can be two layers of encryption
    // inner and outer. It could be encrypted & signed, with it being either
    // encrypted on the outer layer and signed on the inner, or vice versa.
    // We want to ensure that this loop breaks out after either
    // 1. there were 2 layers sign/encrypted or encrypted/signed
    // 2. there was an error
    int layers=0;
    while(!done && layers < 2) {
    output_sink = new ByteArrayOutputStream();
    layers++;
         try {
    // This step must be don't before any cryptographic operations. It lets the SMIMEv2 class
    // figure out what it has as an input and where to place the output
    smimer.attachStreams(input_source, true, output_sink, false, false);
    catch (JSMTException jse) {
    // This is common since unencrypted and unsigned data cannot perform this function
    // Ideally, Baltimore says to use the type SMIMEv2.TYPE_DATA, but it never gets this
    // far since this fails.
    // We will skip the attempts to decrypt/verify the signature, since we know we won't
    // be able to interpret what type of message it is.
    smimeRecognized=false;
    // Will only be one layer
    done=true;
         log.debug("SMIME recognized: " + smimeRecognized);
    if(smimeRecognized) {
    // Get the S/MIME message type
    int nextdata = smimer.getMessageType();
    log.info("SMIME message type: " + nextdata);
    if (nextdata == smimer.TYPE_SIGNED) { // Signed message
    wasSigned=true;
    boolean matchedSender = false;
    // Didn't know you could have multiple "from" in an email address
    // Right now, only one of the "froms" has to have a certificate
    for(int s=0; s < senders.length; s++) {
    // get the sender's address
    String from_sender = senders[s].getAddress();
    try {
    // retrieve the certificates from the LDAP
    JCRYPTO_X509Certificate[] senderCerts = null;
    senderCerts = SecureEmailHelper.getCertificatesFromLDAP(from_sender);
    if(senderCerts!=null) {
    // verify() needs to take in a chain of certificates
    com.baltimore.jsmt.pkcs7.CertificateChain cc= new com.baltimore.jsmt.pkcs7.CertificateChain();
    // create certificate chain
    for(int k=0; k < senderCerts.length; k++) {
    cc.addCertificate(senderCerts[k]);
    // verify the Certificate Chain against the message's certs
    if(smimer.verify(cc)) {
    // found a match, the message was verified
    matchedSender=true;
    break;
    else
    log.error("Could not verify the sender" + from_sender);
    done=true;
    catch(NamingException ne) {
    log.error("There was a problem connecting to the LDAP for " + from_sender,ne);
    done=true;
    // if none of the senders matched, we need to not process
    // the email message, since it will be unreadable
    if(!matchedSender) {
    StringBuffer sendString = new StringBuffer();
    for(int s=0; s < senders.length; s++) {
    String from_sender = senders[s].getAddress();
    sendString.append(" : " );
    sendString.append(from_sender);
    processMessage = false;
    log.error("Could not find certificate for any of the senders" + sendString.toString());
    done=true;
    else if (nextdata == smimer.TYPE_ENVELOPED) { // Encrypted message
    log.debug("SMIME Encrypted message!");
    wasEncrypted = true;
    try {
    log.debug("SMIME Decrypting message...");
    // Decrypts the message
    smimer.openEnvelope();
    catch (JSMTException jse) {
    // Could not decrypt message
    log.error("Could not decrypt message: " + jse.getMessage (), jse);
    processMessage = false;
    done=true;
    else {
    log.debug("Unrecognized type");
    // doesn't seem to get here since Baltimore toolkit doesn't accept
    // nonencrypted, nonsigned emails (it should though). Keep here for future
    // releases of the toolkit
    done = true;
    // Now that we have output_sink,
    // retrieve the bytes
    byte[] processedBytes = output_sink.toByteArray();
    newMessage = new ByteArrayInputStream(processedBytes);
    input_source = new ByteArrayInputStream(processedBytes);
    else {
    // only for the first time around, revert to original
    if(layers==1) {
    // Keep original message
    newMessage = new ByteArrayInputStream(revMessageStr);
    log.debug("wasSigned: " + wasSigned + " wasEncrypted: " + wasEncrypted);
    // create the mime message again
    mimeMessages[i] = new MimeMessage(emailChannel.getSession(),newMessage);
    mimeMessages[i].setFrom (senders[0]);
    mimeMessages[i].setRecipients (Message.RecipientType.TO, recipients);
    // decrypted/verified data is automatically written to output_sink
    input_source.close();
    output_sink.close();
    // If the message wasn't signed, we can still process the message
    // if the settings allow the server to process unsigned messages
    // If not, set the flag to not process this message
    if(!tPhysicalMailbox.getAcceptUnsignedEmail() && !wasSigned) {
         log.info("Server configuration does not allow unsigned emails.");
    processMessage = false;
    // If the message wasn't encrytped, we can still process the message
    // if the settings allow the server to process unencrypted messages
    // If not, set the flag to not process this message
    if(!tPhysicalMailbox.getAcceptUnencryptedEmail() && !wasEncrypted) {
    log.info("Server configuration does not allow unencrypted emails.");
    processMessage = false;
    if(processMessage) {
    MimeMessage m = mimeMessages[i];
    if( maxReceivedEmailSize > 0 && m.getSize() > maxReceivedEmailSize ) {
    try {
    m = constructDummyMsg( m, m.getSize() );
    catch (Exception e) {
    // Add message to a list of messages to be deleted after
    // finished retrieving messages.
    deleteMsgVector.addElement (uniqueID);
    ReceivedMessage receivedMessage =
    new ReceivedMessage (m, uniqueID);
    msgVector.addElement (receivedMessage);
    else {
    log.info("Email could not be processed.");
    deleteMsgVector.addElement (uniqueID);
    catch (EmailException ee) {
    log.error("Email Exception", ee);
    deleteMsgVector.addElement (uniqueID);
    } // mail socket hang fix
    catch (javax.mail.MessagingException e) {
    String message = e.getMessage();
    // if it's a socket hang issue due to network outage, we want to logout and refetch the messages.
    if (message.equals(SOCKET_READ_ERROR)) {
    log.error("Socket timed out. Closing the connection", e);
    messagesOnServer.clear();
    throw new EmailException(

  • DatagramSocket

    Hi I'm trying to build a simple test app using DatagramSocket (AIR 2) and I'm wondering if I absolutely need to use a server in order to communication with other applications on the local network. I have a simple test where I have 2 air apps on my home network, app "A" and app "B" (wireless connected laptop and desktop). I have an animation in app A and app B that are identical. I want the animation in app A to sync with app B, so I want app A to tell app B what frame it's currently on, and app B should update it's frame number accordingly. I'm am pretty new to using DatagramSocket, and I'm not even sure that it's the best thing to use. I just figure UDP would be a lot faster than using TCP in the case where there are a lot of things moving on the screen.
    If anybody can point to examples of sending UDP over a local network that would be great, or post some code, give insights etc.
    Thanks.

    I don't understand what the problem is now.The problem is that 1st time when Timeout occurs it throws exception. In catch block i caught the exception and call some function to perform some task. up to here every thing is fine but problem comes when loop iterates for 2nd time* the socket hangs and doesn't throw any exception when Timeout occurs. I m not sure whether Timeout occurs or not. Here is some piece of code.
    Some Code Here......
    try {
          mnSocket = new DatagramSocket(PORT);
          mnSocket.setSoTimeout(10 * 1000);
          mnSocket.setSendBufferSize(bufferSize);
          mnSocket.setReceiveBufferSize(bufferSize);
          mnSocket.setSoTimeout(10 * 1000);
          sendSolic = new SenderThread(mnSocket, 2);
          solicPacket = new DatagramPacket(buffer, buffer.length);
          while (true) {
            try {
              mnSocket.receive(solicPacket);
              Some Code Here...........
            catch (SocketTimeoutException ste) {
              sendSolic.start();
            Some Code Here........
        catch (SocketException se) {
          se.printStackTrace();
        catch (IOException ioe) {
          ioe.printStackTrace();
       Some Code Here........

  • Stuck on CLOSE_WAIT

    I opened a socket between two machines (Linux-Linux).
    The problem is when one of the sides close its socket the socket hangs on the other side (CLOSE_WAIT) till it closes it explicitly.
    When I run the same thing on Windows machine the socket close on both machines.
    Is there any way to work atound this?
    Thanks,
    Guy

    Try running this server and client. What happens?
    You really, really, really need to close your sockets.
    import java.net.*;
    import java.io.*;
    public class Accept
        public static void main(String[] args)
         throws Exception
            ServerSocket serverSocket = null;
         java.util.LinkedList sockets = new java.util.LinkedList();
            try {
                serverSocket = new ServerSocket(6666);
            } catch (IOException e) {
                System.err.println("could not listen on port 6666: " + e);
                System.exit(1);
            while (true) {
             Socket socket;
             try {
              socket = serverSocket.accept();
             } catch (IOException e) {
              System.err.println("accept failed: " + e);
              Thread.sleep(1000); // Avoid buzz loop
              continue;
             sockets.add(socket);
             System.out.println("accepted " + sockets.size() + " clients");
    import java.net.*;
    import java.io.*;
    public class Connect
        public static void main(String args[])
         throws Exception
         while (true) {
             Socket socket = new Socket("localhost", 6666);
             socket.close();
    }

  • Kernel Panic Then Broken Bluetooth

    I've used bluetooth to transfer photos and movies on and off my LG VX8600 for months, but tonight while I was doing so, my computer had a 'kernel panic' (it forced me to due a restart with the power button), and now it seems there's something wrong. My computer and phone can find one another and even seem to connect, but will not communicate correctly. When I go to browse the phone, I get the error "The last operation failed: bad request." I have never had this problem before, and now I get it every time. I have tried unpairing and repairing, but the problem persists

    Feh, of course right after posting this, I figured it out.
    I had an ssh-agent socket hanging around, apparently that did it.
    +j

Maybe you are looking for