Connection timed out: connect at com.sun.mail.imap.IMAPStore.protocolConne

Hi ,
Recently, my team need to work with javamail. Here I got a problem: when I run the application in my personal home network , it goes on very well. When I run the program in my company env, it gives error info:
Exception in thread "main" javax.mail.MessagingException: Could not connect to SMTP host: smtp.gmail.com, port: 465;
nested exception is:
java.net.ConnectException: Connection timed out: connect
at com.sun.mail.smtp.SMTPTransport.openServer(SMTPTransport.java:1706)
at com.sun.mail.smtp.SMTPTransport.protocolConnect(SMTPTransport.java:525)
at javax.mail.Service.connect(Service.java:313)
The resource is :
import java.security.Security;
import java.util.Date;
import java.util.Properties;
import javax.mail.Authenticator;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
*Use Gmail
public class GmailSender {
public static void main(String[] args) throws AddressException, MessagingException {
Security.addProvider(new com.sun.net.ssl.internal.ssl.Provider());
final String SSL_FACTORY = "javax.net.ssl.SSLSocketFactory";
// Get a Properties object
Properties props = System.getProperties();
//Add proxy for GmailSender
//especially here, I am not sure whether the proxy really works. In home network, it needn't proxy to run successfully.
// props.setProperty("proxySet","true");
// props.setProperty("socksProxyHost","148.87.19.20"); // This IP address is our proxy server address
// props.setProperty("socksProxyPort","80");
props.setProperty("mail.smtp.host", "smtp.gmail.com");
props.setProperty("mail.smtp.socketFactory.class", SSL_FACTORY);
props.setProperty("mail.smtp.socketFactory.fallback", "false");
props.setProperty("mail.smtp.port", "465");
props.setProperty("mail.smtp.socketFactory.port", "465");
props.put("mail.smtp.auth", "true");
final String username = "XXX";
final String password = "XXX";
Session session = Session.getDefaultInstance(props, new Authenticator(){
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(username, password);
// -- Create a new message --
Message msg = new MimeMessage(session);
// -- Set the FROM and TO fields --
msg.setFrom(new InternetAddress(username + "@gmail.com"));
msg.setRecipients(Message.RecipientType.TO,
InternetAddress.parse("[email protected]",false));
msg.setSubject("Hello");
msg.setText("How are you");
msg.setSentDate(new Date());
Transport.send(msg);
System.out.println("Message sent.");
Will you please help me to review my code and give me some suggestions ?

No point looking at the code. The error message says the code can't connect to the server you are trying to connect to, so presumably there's a firewall or something like that preventing the connection. Talk to your network people.

Similar Messages

  • Java.lang.NoSuchMethodException: com.sun.mail.imap.IMAPStore.

    All:
    I have completed the following:
    1. Downloaded the JavaMail 1.4.2 API.
    2. From this downloaded API I had extracted the mail.jar file (timestamp 2009-02-26 13:28) to my C:\Program Files\Tomcat 6.0\lib directory
    3. Downloaded the jaf-1_0_2-upd2 API
    4. From this downloaded API I had extracted the activation.jar file (timestamped 2005-05-07 21:14) also to my C:\Program Files\Tomcat 6.0\lib directory.
    In Eclipse I have created a simple JSP page that calls a POJO that is to read a particular email box using IMAP. In this POJO I have code to set up the Properties, Session and Store objects as such:
    Line 1 Properties properties = System.getProperties();
    Line 2 properties.put("mail.from", "[email protected]");
    Line 3 properties.put("mail.debug","true");
    Line 4 session = Session.getDefaultInstance(properties, null);
    Line 5 session.setDebug(debug);
    Line 6 printData("About to get store object...");
    Line 7 store = session.getStore("imap");
    In eclispe, I click "Debug on Server" and Tomcat starts, begins to display my JSP and then I am dropped on the line of code in my POJO where I set a breakpoint (Line 1). Now I single step through the code. The code throws the following execption when it executes line 7 of the above code :
    (Line 6 ==>) About to get store object...
    DEBUG: getProvider() returning javax.mail.Provider[STORE,imap,com.sun.mail.imap.IMAPStore,Sun Microsystems, Inc]
    java.lang.NoSuchMethodException: com.sun.mail.imap.IMAPStore.<init>(javax.mail.Session, javax.mail.URLName)
         at java.lang.Class.getConstructor0(Unknown Source)
         at java.lang.Class.getConstructor(Unknown Source)
         at javax.mail.Session.getService(Session.java:782)
         at javax.mail.Session.getStore(Session.java:574)
         at javax.mail.Session.getStore(Session.java:536)
         at javax.mail.Session.getStore(Session.java:515)
         at emailTest.readEmails.processMail(readEmails.java:62)
         at emailTest.readEmails.<init>(readEmails.java:24)
         at org.apache.jsp.emailTest_jsp._jspService(emailTest_jsp.java:94)
         at org.apache.jasper.runtime.HttpJspBase.service(HttpJspBase.java:70)
         at javax.servlet.http.HttpServlet.service(HttpServlet.java:717)
         at org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:374)
         at org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:342)
         at org.apache.jasper.servlet.JspServlet.service(JspServlet.java:267)
         at javax.servlet.http.HttpServlet.service(HttpServlet.java:717)
         at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:290)
         at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
         at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:233)
         at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:191)
         at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:128)
         at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:102)
         at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:109)
         at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:286)
         at org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:845)
         at org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:583)
         at org.apache.tomcat.util.net.JIoEndpoint$Worker.run(JIoEndpoint.java:447)
         at java.lang.Thread.run(Unknown Source)
    There are no jar files defined in my project's classpath. The only jar file found in the project is in the WEB-INF\lib folder wherein I have a jndi.jar (timstamp 5/5/2009 8:10AM) file.
    I put the activation.jar file and the mail.jar file in my Tomcat.6\lib folder according item 4 of the JavaMail Sessions section of the Apache Tomcat JNDI Resources HOW_TO found here: http://tomcat.apache.org/tomcat-6.0-doc/jndi-resources-howto.html
    Can anybody please tell me what I need to do to get around this error? Do I perhaps have the wrong versions of one or more jar files?
    FYI: I have also put these same two jar files in my projects classpath and still recevied the same exception. Because I am invoking a POJO from a JSP should these jar files be in my projects classpath in addition to the tomcat\lib directory, or should they only be in the projects' classpath?
    Thanks to all for your time in responding.
    Gary

    bshannon:
    Thank you for your resonse. Your response got me to thinking that my instance of Ecliplse that I had had running yesterday was behaving a little strangely so this morning I closed everything I had running on my workstation and closed down the machine and rebooted. When I finally opend up Eclipse again and ran my JSP program calling my POJO, the code no longer threw the exception. Apparently Eclipse can have its tempermental moments.
    Also, let it be known that while everything is working for me now, I performed a small experiment. I moved the activiation.jar and mail.jar from my project\WEB-INF\lib folder and put them in the the C:\Program Files\Tomcat 6.0\lib directory. Then, when I ran my program I once again recieved the java.lang.NoSuchMethodException error. When I moved these jar files back from the Tomcat diretory to my project\WEB-INF\lib directory, the program worked just fine.
    Thanks again
    Gary

  • [C4003] Connection timed out: connect

    I have i problem when trying to connect to JMS resource through JMSConnection factory on a remote machine. I have standalone client with wich I can connect if a run it on the same machine that AppServer is running. When I try to connect from a remote machine I see SJSMQ JMS Resource Adapter starting... and than i get following error:
    com.sun.messaging.jmq.jmsclient.ExceptionHandler throwConnectionException
    WARNING: [C4003]: Error occurred on connection creation [machinename:7676]. - cause: java.net.ConnectException: Connection timed out: connect
    There are no errors in server log.
    I have set java options -Dorg.omg.CORBA.ORBInitialHost and -Dorg.omg.CORBA.ORBInitialPort when running standalone client.
    I've also created connectionFactory in appServer on client machine that points to remote machine and have succesfully connected to JMS that way.
    So why can't I connect directly to remote machine? Any suggestions?
    Thnx.
    Marko

    No point looking at the code. The error message says the code can't connect to the server you are trying to connect to, so presumably there's a firewall or something like that preventing the connection. Talk to your network people.

  • FTPS receiver side - Connection problem:connection timed out: connect

    Hi experts,
    I must connect to an external server to send files with FTPS.
    I have created receiver CC with connection security: FTPS for control and data connection
    Command order: TLS, USER, PASS, PBSZ, PROT
    Connect mode: per file transfer
    port : 990 (given by third part)
    data connection: passive (suggested by third part)
    My problem is that communication channel raise a connection timed out error, see below for log.
    I've already followed the steps suggested by this thread:
    FTPS Transfer Failing with Connection Timeout
    but no luck.
    Thanks
    Fabio Boni
    2011-05-18 12:21:01 Success Connecting to FTP server "ftps.xxx.xxx.it"
    2011-05-18 12:21:02 Success Write to FTP server "ftps.xxx.xxx.it", directory "/in", -> file "Delivery20110518-122102-155.xml"
    2011-05-18 12:21:02 Success Transfer: "BIN" mode, size 1760 bytes, character encoding -
    2011-05-18 12:21:23 Error Attempt to process file failed with java.net.ConnectException: Connection timed out: connect
    2011-05-18 12:21:23 Error Exception caught by adapter framework: Connection timed out: connect
    2011-05-18 12:21:23 Error MP: Exception caught with cause com.sap.aii.af.ra.ms.api.RecoverableException: Connection timed out: connect: java.net.ConnectException: Connection timed out: connect
    2011-05-18 12:21:23 Error Delivery of the message to the application using connection File_http://sap.com/xi/XI/System failed, due to: com.sap.aii.af.ra.ms.api.RecoverableException: Connection timed out: connect: java.net.ConnectException: Connection timed out: connect.

    As Fabio said, the file adapter log return this log:
    2011-05-18 12:21:01 Success Connecting to FTP server "ftps.xxx.xxx.it"
    2011-05-18 12:21:02 Success Write to FTP server "ftps.xxx.xxx.it", directory "/in", -> file "Delivery20110518-122102-155.xml"
    2011-05-18 12:21:02 Success Transfer: "BIN" mode, size 1760 bytes, character encoding -
    2011-05-18 12:21:23 Error Attempt to process file failed with java.net.ConnectException: Connection timed out: connect
    Seem that FTP access into server is executed successfully and adapter write file, but raise timeout exception.

  • OpenMarket sms api gives "Connection timed out: connect"

    Hello All,
    I am new to web applications with sms services.
    I am trying to send sms from my java application to mobile device. But I am getting below error.
    Aug 25, 2010 10:55:58 AM com.eha.sms.ema.EMACMMessageSendProxy init
    INFO: Move to send the receiver initialization.
    Destination address = +**********
    Source addres = +*****
    Sending message to Simplewire...
    REQUEST XML ==
    <?xml version="1.0" ?>
    <request version="3.0" protocol="wmp" type="submit">
         <user agent="Java/SMS/2.9.16"/>
         <account id="******************" password="***************"/>
         <option type="production"/>
         <source ton="0" address="+*****"/>
         <destination ton="0" address="+**********"/>
         <message udhi="false" text="Hello World!"/>
    </request>
    protocol: http
    remote host: ******Some site given to us by open market people that opens on browser**********
    remote port: 8080
    remote file: /wmp
    {main} [10:55:58.722] Conn: added module com.simplewire.http.RetryModule
    {main} [10:55:58.725] Conn: added module com.simplewire.http.AuthorizationModule
    {main} [10:55:58.726] Conn: added module com.simplewire.http.DefaultModule
    {main} [10:55:58.747] Conn: Creating Socket: smsc-01.openmarket.com:8080
    {main} [10:56:19.759] Conn: java.net.ConnectException: Connection timed out: connect
         at java.net.PlainSocketImpl.socketConnect(Native Method)
         at java.net.PlainSocketImpl.doConnect(Unknown Source)
         at java.net.PlainSocketImpl.connectToAddress(Unknown Source)
         at java.net.PlainSocketImpl.connect(Unknown Source)
         at java.net.SocksSocketImpl.connect(Unknown Source)
         at java.net.Socket.connect(Unknown Source)
         at java.net.Socket.connect(Unknown Source)
         at java.net.Socket.<init>(Unknown Source)
         at java.net.Socket.<init>(Unknown Source)
         at com.simplewire.http.HTTPConnection$_A.run(Unknown Source)
    Message was not sent!
    Error Code: 106
    Error Description: A connection could not be established with the Simplewire network. Connection timed out: connect
    Error Resolution:
    The code I am using is as below.
    private void config()
              Properties properties = new Properties();
              InputStream smscmReceiver = EMACMMessageSendProxy.class.getClassLoader().getResourceAsStream("sms.properties");
              try
                   properties.load(smscmReceiver);
                   System.out.println(properties.getProperty("SMS.SubscriberID").trim());
                   System.out.println(properties.getProperty("SMS.Password").trim());
                   System.out.println(properties.getProperty("SMS.DestinationAddress").trim());
                   System.out.println(properties.getProperty("SMS.SourceAddress").trim());
                   SMS sms = new SMS();
                   // subscriber settings
                   sms.setRemoteHost(" ******Some site given to us by open market people that opens on browser**********");
                   sms.setDebugMode(true);
                   sms.setRemotePort(8080);
                   sms.setSubscriberID(properties.getProperty("SMS.SubscriberID").trim());
                   sms.setSubscriberPassword(properties.getProperty("SMS.Password").trim());
                   // Message Settings
                   sms.setDestinationAddr(properties.getProperty("SMS.DestinationAddress").trim());          // recipient of message
                   sms.setSourceAddr(properties.getProperty("SMS.SourceAddress").trim());               // originator of message
                   sms.setMsgText("Hello World!");
                   System.out.println("Sending message to Simplewire...");
                   // submit message and check results
                   if (sms.submit())
                        System.out.println("Message was sent!");
         System.out.println("Ticket ID: " + sms.getMsgTicketID());
                   else
                        System.out.println("Message was not sent!");
                        System.out.println("Error Code: " + sms.getErrorCode());
                        System.out.println("Error Description: " + sms.getErrorDesc());
                        System.out.println("Error Resolution: " + sms.getErrorResolution() + "\n");
              } catch (IOException e)
              log.error("Load profile sms.properties failed to send Move.", e);
    I am using windows 7 and the required info from the java code is picked up from a property file.
    destination address is a "+" sign followed by cell number of client in US and I am in diff country.
    source code I am using is "+" sign followed by a short code given by client.
    I am also not aware what short codes are for.
    I am also not sure whether I am passing correct parameters.
    I just followed a demo code from the api's sample file. (open market api......swsms-2.9.16 is the jar used.).
    would like to know If destination address can be my cell number.
    The open market people have configured the demo short code for our SMS messaging account.
    This feature will allow us to test our platform to send and receive SMS messages
    while we are waiting for our dedicated short code.
    Mobile Originated messages MUST start with our assigned keyword(s) to be routed to you.
    We have a few keywords but don't know how to use them.
    Please help!
    Thanks in advance.
    Edited by: Vish_1x1 on Aug 24, 2010 11:06 PM

    I had a same problem.
    It was definately URL and SOAP Action Problem.
    Also, I didnt configure the Proxy too.
    Please dont waste more time in looking inot other configs.
    Just give a careful look at Target URL and SOAP Action, again and again.
    Sweta , Please make this question Answerd , it will be useful for other users.
    And Bahvesh Deserves good points..
    Thanks ,
    Deo.

  • Connection timed out: connect

    Hi!
    i am trying to read a webpage into a string but i am getting error
    Exception in thread "main" java.net.ConnectException: Connection timed out: connectIs there any socket port related error.....ports below 1024 r blocked in our companies unix server.... if so please tell me the solution...
    Bunty
    Following is my code.
    import java.io.*;
    import java.net.URL;
    import java.awt.*;
    import java.net.*;
    public class urlTest {
                    public static void main(String args[]) throws Exception {
               try  { 
                         URL url = new URL ( "http://www.yahoo.com" ) ;
                      URLConnection urlConnection = url.openConnection (  ) ;
                      BufferedReader htmlPage = new BufferedReader ( new InputStreamReader ( url.openStream (  )  )  ) ;
                   String line = "";
                      while (  ( line = htmlPage.readLine (  )  )  != null )   { 
                                  //do something with the html line
                              htmlPage.close (  ) ;
                             urlConnection = null;
                        }  catch ( Exception e )   { 
                             e.printStackTrace (  ) ;
    }

    You most likely need to connect through a proxy server. Figure out the proxy host, port and used protocol (probably http) and then build your URL like this:
    URL url = new URL("http", "yourproxyhost",  80, "http://www.yahoo.com");Fill in the relevant information (80 is the proxy port in the above example, perhaps you need to fill in another port).
    Hope that solves your problem.

  • G6 UI Customization build problem - Connection timed out: connect

    For anyone else who's having the same problem we're having:
    When I run ANT on the ui customization folder, I get this error:
    Buildfile: build.xml
    BUILD FAILED
    C:\plumtree_ui_source\portalui\6.0.x\test\build.xml:14: The following error occu
    rred while executing this line:
    Error reading project file C:\plumtree_ui_source\portalui\6.0.x\test\build_core.
    xml: Connection timed out: connect
    Total time: 21 seconds
    We're running behind a proxy.  ANT has to connect to the Java website to pull down it's DTD.  So, the answer is to first run the following command to configure the proxy, replacing the proxy host, port, username, and password with yours:
    set ANT_OPTS=-Xms128m -Xmx800m -DproxySet=true -DproxyHost=10.0.0.0 -DproxyPort=80 -DproxyUser=myUsername -DproxyPass=myPassword

    Thanks for the post, it fixed my issue!

  • RMI on Debian: Connection Timed Out: connect

    Hi
    I have a Problem with my RMI Server program running under Debian.
    When i start the server it lasts for about 3 minute until the Object is bound to the RMI-Registry.
    I have a simple System.out.println("XXX bound"); statement after binding the registry.rebind(name, stub);
    Well it seems to work because no exception is thrown and i can see the println.
    But the big problem is, that it takes for about 3 minutes until this is done. when i try to connect to the server via the client,
    i get a
    "Connection refused to host: xxxxx; nested exception is:
    java.netConnectException: Connection timed out: connect"
    after a minute, the serverside doesn't make anything, no System.out statement is executed in the remote method.
    it seems that RMI is very slow on my Server machine and i can't figure out why.
    here are the properties set in the server program:
    System.setProperty("java.rmi.server.codebase", "xxxxxx"); //works
         System.setProperty("java.rmi.server.hostname", "xxxx.ath.cx"); //perhaps the problem
         System.setProperty("java.security.policy", "/var/www/dod/xxxxx.policy"); // should be no problemmy client is startet via webstart from the same server an has the lookup code:
    try {
                   registry = LocateRegistry.getRegistry("xxxx.ath.cx"); //perhaps the problem
                   idodsrmi = (XXXServerRMI) registry.lookup("xxxxxxx");
                   usrh = idodsrmi.getUserHandle(args[0], args[1]);
              } catch (AccessException e) {
                   JOptionPane.showMessageDialog(null, e.getMessage());
                   e.printStackTrace();
              } catch (RemoteException e) {
                   JOptionPane.showMessageDialog(null, e.getMessage());
                   e.printStackTrace();
              } catch (NotBoundException e) {
                   JOptionPane.showMessageDialog(null, e.getMessage());
                   e.printStackTrace();
              } this code is executed without throwing an exception, but when i try to call methods on usrh i get the connection timeout...
    i can't see where the problem is, "xxxx.ath.cx" is the domain name my network is available from outside the lan,
    my router forwards port 80 and 1099 to my serverbox
    any ideas about the timeout?

    Yes that was it, i got the clou when i changed the hostname of my debian-box to xxx.ath.cx. after changing to that hostname i got an exception to google for.. ;-) But it's still strange to get no exception when the hostname of my debian-box differs from the dyndns name. it just lasts for about 3 minutes and seems to work...
    Well now im back to an older problem, my server uses hibernate to communicate with a db and when i make 2 .jars (1 hibernate-util with all hibernate related jars and 1 for my project) instead of 1 big jar with all jars i get the exception "No Persistence provider for EntityManager named DOD", thats a strange behavior too because the persistence.xml is at the same place in my project .jar... :-/

  • Com.sun.mail.imap.IMAPFolder close

    Hi everyone,
    We are using BMC Remedy Email Engine with javamail function.
    Why is the message of ''com.sun.mail.imap.IMAPFolder close' message is indicated in stderr.log file' indicated? BMC and we don't know the reason at all. If someone knows, could you please teach us the error cause?
    The detail is below:
    2008/10/07 1:16:10 com.sun.mail.imap.IMAPFolder close
    SEVERE: A6 NO CLOSE Block size illegal for BPOOL.
    javax.mail.MessagingException: A6 NO CLOSE Block size illegal for BPOOL.;
    nested exception is:
         com.sun.mail.iap.CommandFailedException: A6 NO CLOSE Block size illegal for BPOOL.
         at com.sun.mail.imap.IMAPFolder.close(IMAPFolder.java:1003)
         at com.sun.mail.imap.IMAPFolder.close(IMAPFolder.java:935)
         at com.remedy.arsys.emaildaemon.ReceiverModule.terminateIncommingMailbox(ReceiverModule.java:1837)
         at com.remedy.arsys.emaildaemon.ReceiverModule.doWork(ReceiverModule.java:357)
         at com.remedy.arsys.emaildaemon.ThreadBase.run(ThreadBase.java:268)
         at java.lang.Thread.run(Unknown Source)
    Caused by: com.sun.mail.iap.CommandFailedException: A6 NO CLOSE Block size illegal for BPOOL.
         at com.sun.mail.iap.Protocol.handleResult(Protocol.java:294)
         at com.sun.mail.iap.Protocol.simpleCommand(Protocol.java:316)
         at com.sun.mail.imap.protocol.IMAPProtocol.close(IMAPProtocol.java:926)
         at com.sun.mail.imap.IMAPFolder.close(IMAPFolder.java:1000)
         ... 5 more
    Regards,
    NAKAI

    Hi,
    I'm experiencing a quite similar problem in our BMC Remedy Email Engine. IMAP mail integration that has been working for a long time has suddently quit working and now producing error message as below every second instead. NAKAI - did you find any solution to your problem? Anyone else that has experienced any similar?
    Thanks in advance,
    Daniel
    A94819 NO The request is not supported.;
    nested exception is:
         com.sun.mail.iap.CommandFailedException: A94819 NO The request is not supported.
    javax.mail.MessagingException: A94819 NO The request is not supported.;
    nested exception is:
         com.sun.mail.iap.CommandFailedException: A94819 NO The request is not supported.
         at com.sun.mail.imap.IMAPMessage.loadEnvelope(IMAPMessage.java:1063)
         at com.sun.mail.imap.IMAPMessage.getMessageID(IMAPMessage.java:428)
         at com.remedy.arsys.emaildaemon.ReceiverModule.checkAndSkipStoredMessages(ReceiverModule.java:397)
         at com.remedy.arsys.emaildaemon.ReceiverModule.doWork(ReceiverModule.java:275)
         at com.remedy.arsys.emaildaemon.ThreadBase.run(ThreadBase.java:268)
         at java.lang.Thread.run(Unknown Source)

  • Chat System: ConnectException: Connection timed out: connect

    Hi There,
    I am developing a chat system as part of a University project.
    To explain what I have implemented:
    I have three java classes;
    1. Chat Server class which is constantly listening for incoming socket connection on a particular socket:
    while (true)
    Socket client = server.accept ();
    System.out.println ("Accepted from " + client.getInetAddress ());
    ChatHandler c = new ChatHandler (client);
    c.start ();
    2. Chat Handler class uses a thread for each client to handle multiple clients:
    public ChatHandler (Socket s) throws IOException
    this.s = s;
    i = new DataInputStream (new BufferedInputStream (s.getInputStream ()));
    o = new DataOutputStream (new BufferedOutputStream (s.getOutputStream ()));
    public void run ()
    try
    handlers.addElement (this);
    while (true)
    String msg = i.readUTF ();
    broadcast (msg);
    catch (IOException ex)
    ex.printStackTrace ();
    finally
    handlers.removeElement (this);
    try
    s.close ();
    catch (IOException ex)
    ex.printStackTrace();
    protected static void broadcast (String message)
    synchronized (handlers)
    Enumeration e = handlers.elements ();
    while (e.hasMoreElements ())
    ChatHandler c = (ChatHandler) e.nextElement ();
    try
    synchronized (c.o)
    c.o.writeUTF (message);
    c.o.flush ();
    catch (IOException ex)
    c.stop ();
    3. Chat Client class which has a simple GUI and sends messages to the server to be broadcasted to all other clients on the same socket port:
    public ChatClient (String title, InputStream i, OutputStream o)
    super (title);
    this.i = new DataInputStream (new BufferedInputStream (i));
    this.o = new DataOutputStream (new BufferedOutputStream (o));
    setLayout (new BorderLayout ());
    add ("Center", output = new TextArea ());
    output.setEditable (false);
    add ("South", input = new TextField ());
    pack ();
    show ();
    input.requestFocus ();
    listener = new Thread (this);
    listener.start ();
    public void run ()
    try
    while (true)
    String line = i.readUTF ();
    output.appendText (line + "\n");
    catch (IOException ex)
    ex.printStackTrace ();
    finally
    listener = null;
    input.hide ();
    validate ();
    try
    o.close ();
    catch (IOException ex)
    ex.printStackTrace ();
    public boolean handleEvent (Event e)
    if ((e.target == input) && (e.id == Event.ACTION_EVENT)) {
    try {
    o.writeUTF ((String) e.arg);
    o.flush ();
    } catch (IOException ex) {
    ex.printStackTrace();
    listener.stop ();
    input.setText ("");
    return true;
    } else if ((e.target == this) && (e.id == Event.WINDOW_DESTROY)) {
    if (listener != null)
    listener.stop ();
    hide ();
    return true;
    return super.handleEvent (e);
    public static void main (String args[]) throws IOException
    Socket s = new Socket ("192.168.2.3",4449);
    new ChatClient ("Chat test", s.getInputStream (), s.getOutputStream ());
    On testing this simple app on my local host I have launched several instances of ChatClient and they interact perfectly between each other.
    Although when i test this app by launching ChatClient on another machine (using a wi-fi network connection at home), on the other machine that tries to connect to the hosting server (my machine) i get a "connection timed out" on the chatClient machine.
    I have added the port and ip addresses in concern to the exceptions to by-pass the firewall but i am still getting the timeout.
    Any suggestions?
    Thanks!

    Format your code with [ code ] tag pair.
    If you are a young university student I don't understand why current your code uses so many of
    too-too-too old APIs including deprecated ones.
    For example, DataInput/OutputStream should never be used for text I/Os because they aren't
    always reliable.
    Use Writers and Readers in modern Java programming
    Here's a simple and standard chat program example:
    (A few of obsolete APIs from your code remain here, but they are no problem.
    Tested both on localhost and a LAN.)
    /* ChatServer.java */
    import java.io.*;
    import java.util.*;
    import java.net.*;
    public class ChatServer{
      ServerSocket server;
      public ChatServer(){
        try{
          server = new ServerSocket(4449);
          while (true){
            Socket client = server.accept();
            System.out.println("Accepted from " + client.getInetAddress());
            ChatHandler c = new ChatHandler(client);
            c.start ();
        catch (IOException e){
          e.printStackTrace();
      public static void main(String[] args){
        new ChatServer();
    class ChatHandler extends Thread{
      static Vector<ChatHandler> handlers = new Vector<ChatHandler>();
      Socket s;
      BufferedReader i;
      PrintWriter o;
      public ChatHandler(Socket s) throws IOException{
        this.s = s;
        i = new BufferedReader(new InputStreamReader(s.getInputStream()));
        o = new PrintWriter
         (new BufferedWriter(new OutputStreamWriter(s.getOutputStream())));
      public void run(){
        try{
          handlers.addElement(this);
          while (true){
            String msg = i.readLine();
            broadcast(msg);
        catch (IOException ex){
          ex.printStackTrace();
        finally{
          handlers.removeElement(this);
          try{
            s.close();
          catch (IOException e){
            e.printStackTrace();
      protected static void broadcast(String message){
        synchronized (handlers){
          Enumeration e = handlers.elements();
          while (e.hasMoreElements()){
            ChatHandler c = (ChatHandler)(e.nextElement());
            synchronized (c.o){
              c.o.println(message);
              c.o.flush();
    /* ChatClient.java */
    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.*;
    import java.net.*;
    import java.io.*;
    public class ChatClient extends JFrame implements Runnable{
      Socket socket;
      JTextArea output;
      JTextField input;
      BufferedReader i;
      PrintWriter o;
      Thread listener;
      JButton endButton;
      public ChatClient (String title, Socket s){
        super(title);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        socket = s;
        try{
          i = new BufferedReader(new InputStreamReader(s.getInputStream()));
          o = new PrintWriter
           (new BufferedWriter(new OutputStreamWriter(s.getOutputStream())));
        catch (IOException ie){
          ie.printStackTrace();
        Container con = getContentPane();
        con.add (output = new JTextArea(), BorderLayout.CENTER);
        output.setEditable(false);
        con.add(input = new JTextField(), BorderLayout.SOUTH);
        con.add(endButton = new JButton("END"), BorderLayout.NORTH);
        input.addActionListener(new ActionListener(){
          public void actionPerformed(ActionEvent ae){
            o.println(input.getText());
            o.flush();
            input.setText("");
        endButton.addActionListener(new ActionListener(){
          public void actionPerformed(ActionEvent ev){
            try{
              socket.close();
            catch (IOException ie){
              ie.printStackTrace();
            System.exit(0);
        setBounds(50, 50, 500, 500);
        setVisible(true);
        input.requestFocusInWindow();
        listener = new Thread(this);
        listener.start();
      public void run(){
        try{
          while (true){
            String line = i.readLine();
            output.append(line + "\n");
        catch (IOException ex){
          ex.printStackTrace();
        finally{
          o.close();
      public static void main (String args[]) throws IOException{
        Socket sock = null;
        String addr = "127.0.0.1";
        if (args.length > 0){
          addr = args[0];
        sock = new Socket(addr, 4449);
        new ChatClient("Chat Client", sock);
    }

  • HttpUrlConnection: Connection timed out: connect

    I am seeing a small percentage of my customers who cannot connect to my server through my Java program to download program updates. The commonality between the customers is that all (or most) of them seem to be from Australia, but I have some customers in Australia who CAN connect successfully. Probably a red herring.
    The problem is seen when creating a URL connection to a text file to read it. The file contains only 3 lines. Like I said, most users do not have a problem, but some do. Could it be that the connection is actually timing out, and if so, how do I lengthen the timeout? Most users say that they do not even have to wait 5 seconds before the error occurs.
    The user can connect to the URL with a browser and download the files that way, but this is supposed to be an automatic process. They tell me there is nothing wrong with their network. I'm wondering whether they might have a firewall in place, but when I block connections using my software firewall, I get java.net.UnknownHostException instead.
    The code looks roughly like this. I've added printlns recently and have not heard back from the customer with any results.
            String urlString = cUpdateLocation + cUpdateFileName;
             try {
                System.out.println("Create the URL: " + urlString);
                URL url = new URL(urlString);
                System.out.println("Open the URL connection");
                URLConnection urlConn = url.openConnection();
               System.out.println("Get an input stream");
                InputStream inputStream = urlConn.getInputStream();
                System.out.println("Define an input stream reader");
               InputStreamReader iReader = new InputStreamReader(inputStream);
               System.out.println("Define a buffered reader");
                BufferedReader bReader = new BufferedReader(iReader);
               String input = "";
               System.out.println("Read from the buffered reader");
                try {
                    while (input != null) {
                       input = bReader.readLine();
                        if (input != null) {
                            // Ignore blank lines 
                          input.trim();
                            if (input.length() > 0) {
                                System.out.println("input=" + input);
                   System.out.println("Done reading from the buffered reader");
                    success = true;
                } catch (IOException e) {
                   // Catch these IOExceptions here so we can still close the
                    // streams and clean up while we have reference to them
    .                System.out.println("IOException encountered reading from:\n" +
                                      urlString + "\n" + e);
                bReader.close();
            } catch (MalformedURLException e) {
                System.out.println("URL " + urlString + " is malformed.  " +
                                   e.getMessage());
            } catch (IOException e) {
               // This is the exception that I normally see.
                System.out.println("IOException encountered creating stream to " +
                                   "read from:\n" + urlString + "\n" + e);
                e.printStackTrace();

    Did u write the code to handle Proxy server.?
    Though i m not sure but might be clients who are getting error uses proxy server. and other dont have a proxy in their network.
    Iu did not handled proxy u can do this by...
    Properties sysProperties = System.getProperties();
    // Specify proxy settings
    sysProperties.put("proxyHost", "your_proxy_host");
    sysProperties.put("proxyPort", "your_proxy_port");
    sysProperties.put("proxySet", "true");or while running
    use
    java -D option to set these system properties
    hope works
    cheers

  • Connection timed out: connect for ebMs messages

    Hi
    We are facing a problem while posting an outbound message in ebMS. We encounter the following error.
    Machine Info: (INBAAMPC00933)
    *Transport error: [IPT_HttpSendConnectionRefused] HTTP connection is refused.*
    Connection refused: connect
    Oracle b2b is used at both the ends. The initiating b2b does not have any certificates, while the receiving b2b has a certificate and 2 Delvery Channels (DCs). One of the DC's does not use certificates and that is the one tied to the agreement. So, Iam assuming this error is not due to the certificates. Could you please help me out in this.
    Ranjith

    Hi Ranjith,
    It seems that receiving B2B or any other front end(like any switch) is expecting the initiating B2B to send message over HTTPS.
    Please check whether you are able to ping and telnet the receiving B2B's host name at the port specified in the initiating B2B configuration. Also make sure that this port has HTTP enabled and not HTTPs.
    Let us know the result.
    Regards,
    Anuj

  • Connection timed out, Connection timed out

    I get this message whenever I try to get reconnected to known wireless networks, please help.

    i was updating my iphone and it just stopped, now says i have to restore to have phone load, it also just has a plug and the end of a usb showing on face of phone i also will loose all data pics, music if i restore what can i do to get it to connect and upload data to computer/itunes HELP

  • Error while connecting to Microsoft Exchange server using javamail: "com.sun.mail.util.MailConnectException: Couldn't connect to host, port: host name , 993; timeout -1"

    I am trying to read mails from my outlook microsoft exchange server. Following is the code:
    public void readEmailsFromOutlook(/*String host, String username, String password*/ ) throws MessagingException, IOException {
          String host = "hostname";
          String username = "domain\\username";
          String password = "password"
          // Create empty properties
          Properties props = System.getProperties();
          props.setProperty("mail.smtp.auth","true");
          props.setProperty("mail.store.protocol","imaps");
          props.setProperty("mail.imap.auth.plain.disable","true");
          props.setProperty("mail.imap.host",host);
          props.setProperty("mail.imap.port","993");
          props.setProperty("mail.imap.user",username);
          props.setProperty("mail.imap.pwd",password);
          props.setProperty("mail.imap.debug","true");
          props.setProperty("mail.imap.ssl.protocols","SSL");
          props.setProperty("mail.imap.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
          props.setProperty("mail.imap.socketFactory.fallback", "false");
          props.setProperty("mail.imap.socketFactory.port", "993");
          // Get session
                     Session session = Session.getInstance(props, new ExchangeAuthenticator(username, password));
          session.setDebug(true);
          // Get the store
          Store store = session.getStore("imaps");
          //Store store = session.getStore();
          store.connect(host, username, password);
          // Get folder
          Folder folder = store.getFolder("INBOX");
          folder.open(Folder.READ_ONLY);
          BufferedReader reader = new BufferedReader(new InputStreamReader(
              System.in));
          // Get directory
          Message message[] = folder.getMessages();
          for (int i = 0, n = message.length; i < n; i++) {
            System.out.println(i + ": " + message[i].getFrom()[0] + "\t"
                + message[i].getSubject());
            System.out.println("Read message? [YES to read/QUIT to end]");
            String line = reader.readLine();
            if ("YES".equalsIgnoreCase(line)) {
              System.out.println(message[i].getContent());
            } else if ("QUIT".equalsIgnoreCase(line)) {
              break;
          // Close connection
          folder.close(false);
          store.close();
    But it threw the following error:
    DEBUG: setDebug: JavaMail version 1.5.1
    DEBUG: getProvider() returning javax.mail.Provider[STORE,imaps,com.sun.mail.imap.IMAPSSLStore,Oracle]
    DEBUG IMAPS: mail.imap.fetchsize: 16384
    DEBUG IMAPS: mail.imap.ignorebodystructuresize: false
    DEBUG IMAPS: mail.imap.statuscachetimeout: 1000
    DEBUG IMAPS: mail.imap.appendbuffersize: -1
    DEBUG IMAPS: mail.imap.minidletime: 10
    DEBUG IMAPS: trying to connect to host <hostname>,port 993, isSSL true
    com.sun.mail.util.MailConnectException: Couldn't connect to host, port: 10.75.250.60, 993; timeout -1;
      nested exception is:
    java.net.ConnectException: Connection refused: connect
    at com.sun.mail.imap.IMAPStore.protocolConnect(IMAPStore.java:693)
    at javax.mail.Service.connect(Service.java:345)
    at javax.mail.Service.connect(Service.java:226)
    at com.capgemini.utilities.Utilities.readEmailsFromOutlook(Utilities.java:1261)
    Whats wrong with my code?
    Please help!!!!

    You're using the "imaps" protocol, but you've set properties for the "imap" protocol.  Change all the property names from mail.imap.* to mail.imaps.*.
    Also, get rid of all the socket factory properties.
    If you still can't connect, see these connection debugging tips.
    Most likely you're using the wrong host name or port number.  In almost all cases, it's better to just let JavaMail choose the correct port number.

  • Sender Mail Adapter configuration connection timed out

    Hi All,
    I am setting up a simple sender mail scenario to test if my mailadapter works.
    But I receive a error message in the Sender Communication Channel I receive this error:
    "exception caught during processing mail message; java.net.ConnectException: Connection timed out: connect"
    I tested File Sender to Mail Receiver Scenario it worked fine.
    But Sender Mail to File Receiver is not working and giving above exception.
    Mail Sender SetUp
    pop://xx.xxx.xx.xx
    In User and Password I have given my Lotus Notes Server user & password credentials
    Pls suggest

    HI Rachit,
    Have you seen the thread
    Sender Mail Adapter
    There it is mentioned that the Lotus notes mail id shoudl be POP3 enabled. Try doing that
    Regards
    Suraj

Maybe you are looking for

  • Edge animation-images are not displayed on my dreamweaver-site

    Hello, could someone please help me? My animation, which is inserted into  a Dreamweaver-website, shows no pictures - only text elements when you open the page in the browser. In the live view and preview in the browser the images are displayed but o

  • How do i clear the qRFC queue in a R/3 sandbox

    Hi All,     I just built a R/3 4.7B sandbox and we are going to perform an upgrade on it. But before we do that we need to clear the qRFC queue. Can anyone please let me know as to how i go about in clearing the qRFC queue. Thanks Anil

  • Check in MIGO for the excise tab

    Hello Guru's, We are trying to put the check for the Sub Transaction type in MIGO. As we capture and post Excise in MIGO itself. We have tried but none of the Excise CIN exits are firing in the MIGO transaction. Can anyone please suggest any BADI or

  • Popup (hyperlink) closes when using scroll bar

    Robohelp (RH8).  The popup (hyperlink) closes when I use the scroll bar.  However, if I use the mouse wheel to scroll the popup does not close.  I am sure this is normal behavior however I would like it the stay open when using the scroll bar.  Is th

  • 3月24日产品生命周期管理(PLM)的免费讲座 --- 结束了

    主题:将信息转变为战略资产u2014企业信息管理专题(在线)研讨会 时间:3月17日下午两点 演讲人:SAP资深顾问 杜一帆 概要:全面的信息管理功能,有助于企业用户为业务交易处理.商务智能.数据仓库.数据迁移和主数据管理等关键行动计划提供可信的数据.SAP资深方案构架师为您详解SAP企业信息管理解决方案如何帮助您的企业将信息转变为战略资产. [点击这里注册|http://www.bestsapchina.com/Incoming_event.aspx?utm_source=webinar-om