Massive system load on socket connect

Hi all,
I have some strange problem connecting to a server. I am using the JDK1.4.1 and connect with a timeout of 1000ms, so I would expect Java to honor this, but on some connections the connect call itself takes up to 5 seconds. During this time the processor load goes very hight and the
client is so busy that you cannot even press a button in some GUI.
I have 4 clients which connect to the same socket in parallel but they are all in own threads.
Another thing worth to mention is that I also try to connect to hosts,
where no route exists to them (I need this because I want my system to also work properly when the customer has some errors in his network
configuration and some servers may not be reachable).
Any ideas??

sorry for the missing information:
the problems occur on Windows XP Pers., I havent seen any problems
yet with linux (I'm using Debian) but I don't run the same
configuration on linux (the client side is Windows, the servers all
run on Debian).
The load is definitely operating system load because it occurs when I watch some of the connect()'s block for about 5 seconds - my application does nothing but wait for the connect to come back.

Similar Messages

  • Too many open socket connections causing ColdFusion to crash?

    I’m currently working on an e-commerce site which sends and receives information to/from the client’s order management system via XML over a TCP/IP socket.  It uses a very old java-based custom tag called CFX_JSOCKET (which appears to have been written in 2002) to open the socket, send the data, and get the response.  The code that calls the custom tag and sends/receives data from the OMS pre-dates my working on the site, but its always worked, so I haven’t paid it much attention.
    Back in the summer of 2009 we started experiencing issues with ColdFusion (v.7 on Window 2003 at the time) locking up on a more and more frequent basis, until it ultimately became a daily issue.  After extensive research we narrowed the issue down to the communication between the web server and our client’s order management server.  It seemed the issue with ColdFusion hanging was either related to there being too many connections open, or to these connections hanging and resulting in dead threads.  This an educated guess based on a blog post I’d seen online, not actual monitoring of either CF or the TCP/IP connections.  As soon as we dialed back the timeout on the CFX_JSOCKET tag from 20 seconds to 10, the issue disappeared, so we left it at that and moved on.
    Fast forward to this January. The site is hosted at a new location, on a 64-bit Windows 2008 box running ColdFusion 9.  Over the years traffic on the site has continued to grow.  The nature of the clients business means that August and January are their business times of the year (back to school for college kids) and in January ColdFusion once again started locking up on an almost-daily basis.  
    One significant difference is that the address cleansing software that previously ran on the box and was used to verify shipping addresses is not available for 64-bit, so when we moved to the new server last summer, that task was moved to the client’s order management software and handled via XML like all other interaction with that system. However, while most XML calls to that server (order input, inventory check, etc) take under a second to complete, the address cleansing call regularly takes over 5 seconds to return data, and frequently times out. 
    Once we eliminated the address cleansing call from the checkout process, ColdFusion once again stopped locking up regularly.  So it appears that once again it’s the communication between the web server and the order management server that’s causing problems. We currently have that address cleansing call disabled on the web site in order to keep ColdFusion from crashing, but that’s not a long term solution.
    We don’t have, nor can I find online, the source code for the CFX_JSOCKET custom tag, so I decided I’d write some CF code utilizing the java methods to open the socket, send the data, get the response, and close the connection.  My test code is working fine (under no load).  However, in trying to troubleshoot an issue I had with it, I started monitoring the TCP/IP connections using TCPView.  And I noticed that all the connections to the order management server, whether opened via the custom tag or my new code, remain open in either a TIME_WAIT or FIN_WAIT2 status for well over 2 minutes, even though I know for a fact that my new code is definitely closing the connection from the web server side. 
    They do all close eventually, but I’m wondering 1. Why they’re remaining open that long; 2. Is that normal; and 3. If all these connections remaining open could be what’s causing ColdFusion to choke. 
    Does this sound plausible?  If so, does anyone have any suggestions/recommendations about how to fix it?  My research seems to indicate this might be a matter of the order management system not closing the connection on its end, but I’m in way over my head, and before I go to client and tell them it’s their OMS causing the issue, I need to feel a little more confident that I’m on the right track. 
    Any help or advice would be very greatly appreciated.  And thanks for taking the time to read through my long-winded explanation of the problem.
    Set-up details:
    ColdFusion Version: 9,0,0,251028  Standard 
    Operating System: Windows Server 2008 
    Java Version: 1.6.0_14 
    Java VM Name: Java HotSpot(TM) 64-Bit Server VM 
    Java VM Version: 14.0-b16 
    Thanks,
    Laurie

    Hi Laurie,
    Not aware of custom tag called CFX_JSOCKET. I guess the process you described very well is consuming a resource then you are getting a problem. Trick is what parameter to adjust. Perhaps you are running out of one the threads in CFadmin > Server Settings > Request Tuning.
    I expect if you enable CF Metrics logging where you can log the threads and other resources then you can find out which parameter needs adjusting. Let me know if you want some details on enabling CF Metrics. Perhaps others will have much better idea than me and help without the overhead of logging.
    The other interesting thing is you are using CF9.0.0. Do you have some reasons for not being on updater1 CF9.0.1?
    HTH, Carl.
    PS I posted before however seems to have gone, just hope does not come back and then I have posted twice.

  • Socket connection

    Hi,
    I want to connect swf file running in www.xxx.com via socket
    to www.xxx.com:25
    My crossdomain.xml looks like:
    <?xml version="1.0"?>
    <!DOCTYPE cross-domain-policy SYSTEM "
    http://www.macromedia.com/xml/dtds/cross-domain-policy.dtd">
    <cross-domain-policy>
    <allow-access-from domain="www.xxx.com/*" to-ports="25"
    />
    </cross-domain-policy>
    But when i do remote debug i see this error:
    Se ha detenido la conexión con www.vescovoweb.com:25 -
    no se permite desde
    http://www.xxx.com/ct.swf
    securityErrorHandler: [SecurityErrorEvent
    type="securityError" bubbles=false cancelable=false eventPhase=2
    text="Error #2048: Violación de la seguridad Sandbox:
    http://www.xxx.com/ct.swf no
    puede cargar datos desde www.xxx.com:25."]
    Anyone can help me?

    It's the socket constructor:
    public function SendMail(host:String = null, port:uint = 0)
    try
    Security.loadPolicyFile("
    http://" + host + "/crossdomain.xml");
    } catch (error:Error){
    trace('NO crossdomain.xml\n'+error.message+'\n');
    socket = new Socket();
    configureListeners(socket);
    try {
    trace("Trying to connect to " + host + ":" + port + "\n");
    socket.connect(host, port);
    } catch (error:Error) {
    trace(error.message + "\n");
    socket.close();
    In the third row i load the policy file but i suppose the
    loading is fine because flash don't tell me any error when it's
    load.
    Any suggestion?

  • System load application (stress measurement)

    Hi,
    I am about to create a Benchmark application. The main purpose of the application is to compare performance between Linux and Windows NT. Two PCs equipped with Gigabit Ethernet cards are to be connected point-to-point.
    (*PC, Sender*)---->UDP/TCP channel---->(*PC, Receiver)
    One PC will load the other PC by sending either TCP or UDP packets. I have already written both receiver and sender applications, but I need to monitor the system load at the receiving end. My question is whether it is possible to perform the following actions with Java code.
    * Measure the CPU usage on the receiving PC.
    * Monitor the level of PCI bus traffic.
    * I want to monitor the memory load. (more precise than freeMemory() and totalMemory() )
    If any of these options are possible, where can I find more info/sample code ? I have heard something about JNI, but I don't really know what that is.

    The comparison would be unfair (by your definition of unfair) in Java, too, since the JVMs for both platforms are different.
    If you are dealing with time, though, 500 milliseconds is 500 milliseconds, no matter what language you write it on or what platform you run it on. If you use VC++ for the Windows stuff, make sure you disable Microsoft extensions so you have some ANSI standard code that will compile with gcc.
    Since you are trying to compare operating systems, make sure both machines are using the same processors (and motherboards with the same PCI bus architecture), too. And have the same amount of memory, which is the same speed and architecture on both. Their hard drives should be roughly the same speed, too. The PCI bus usage could vary with network cards, so having the same network cards will be a plus. What it seems to come down to is that you are going to end up measuring the performance of the socket library implementations on both machines.
    As far as JNI goes, all it is is a way to write native code and use it in your Java application. I don't know much about it, search around for some examples. There's a tutorial, somewhere, too. Some dude on here, tpritchet, seems to know a lot about it.
    Jason

  • Maximum number of socket connections?

    Hi there,
    I've done a test to check what is the maximum simultanenous socket clients can connect to a socketserver.
    The code is as follows:
    --------- The Server ------------
    import java.net.*;
    public class Server {
         public void start() {
              int counter = 0;
              try {
                   ServerSocket server = new ServerSocket(9999);
                   System.out.println("Server started.");
                   while (true) {
                        Socket connection = server.accept();
                        counter++;
                        System.out.println("Client " + counter + " connected.");
         catch (Exception ex) {
         public static void main(String args[]) {
              Server obj = new Server();
              obj.start();
    ----------- The Client -----------
    import java.net.*;
    public class Client {
         public static final int NUMBER_OF_CLIENTS = 20; // number of simultaneous connections.
         class ClientThread implements Runnable {
              Thread t;
              int id;
              public ClientThread(int id) {
                   t = new Thread(this);
                   this.id = id;
                   t.start();
              public void run() {
                   try {
                        Socket connection = new Socket(InetAddress.getLocalHost(), 9999);
                        System.out.println("Client " + id + " connection OK!");
                        //connection.close();
              catch (Exception ex) {
                   System.out.println("Client " + id + " connection Failed!");
         public void start() {
              for (int i = 0; i < NUMBER_OF_CLIENTS; i++)     {
                   ClientThread t = new ClientThread(i+1);
         public static void main(String args[]) {
              Client c = new Client();
              c.start();
    Test env: Windows XP Sp1
    Test results: There is atleast one client which has connection refused.
    Questions:
    1) Is the situation platform-dependent?
    2) Is it possible to configure connection limit on server socket?
    Thanks for paying attention.
    Trung

    Oh, it doesn't work!
    Client 1 connection OK!
    Client 20 connection OK!
    Client 19 connection OK!
    Client 18 connection OK!
    Client 17 connection OK!
    Client 16 connection OK!
    Client 11 connection OK!
    Client 10 connection OK!
    Client 15 connection OK!
    Client 14 connection OK!
    Client 13 connection OK!
    Client 9 connection OK!
    Client 8 connection OK!
    Client 3 connection OK!
    Client 4 connection OK!
    Client 5 connection OK!
    Client 6 connection Failed!
    Client 7 connection Failed!
    Client 2 connection OK!
    Client 12 connection OK!
    I've executed 5 times, the 5th one has showed the
    error.I doubt this has anything to do with a 'limit' in the OS.
    A box can only process so much at once. That includes establishing connections.
    High volume situations are handled by using multiple servers and a front end load balancing router.

  • SAP PCO Socket Connection VS HyperTerminal

    Hi All,
    We're trying to process an IP Barcode Scanner message using PCo notifications. How should I configure the subscription item / notification so that the received message is captured as using the HyperTerminal software?  Is there any documentation we should be aware of?
    Many Thanks,
    Paul Radulescu

    Hi Steve,
    We did our tests this morning. The source socket connection settings are below:
    I also attached a small log (FScan_Gi.txt) around one scan, where the alert is being raised, and the message is being sent to the destination system dummy transaction which only writes the file in the MII Web space (i.e. FS_msg_03.xml)
    My take on the multiple streams is that the scanner we used is a fixed industrial type one. The label being scanned contains multiple barcodes and the scanner scans all of them at once, delimiting the message with some CONTROL CHARACTERS, giving some headaches going forward.
    If I define an XML query and read the message saves "as is" by the dummy transaction above, I get a nice, but firm message :
    which comes from the control characters inserted by the scanner between the barcodes. PCo transmits the message as is, MII saves it as is, but when I try to open and process it .. I can't. Opening it in a transaction in workbench using the text-loader gives me a "prolog" error
    Funny. I feel like I get the best out of it sometimes
    Definitely I have to get rid of those control characters .. even by truncating the message. There are three barcodes being scanned, I presently need only the last one .. so my question is .. Can I use the expression editor and look for the message content after the "~" sign in the string over there (see FS_msg_03.xml) with something like stringpart('Fscan_GI', ~-location, length-of-the-string-after-~) I code below ?
    I have to wait again for the scanner to be available next Tue and test this without copy-pasting the content in the Value box above, but are you envisioning any possible "prolog" errors in the PCo log this time?
    Cheers,
    Paul.

  • I suppose it is the problem with socket connection,Please help

    Hi,
    I'm trying to build a chat server in Java on Linux OS.I've created basically 2 classes in the client program.The first one shows the login window.When we enter the Login ID & password & click on the ok button,the data is sent to the server for verification.If the login is true,the second class is invoked,which displays the messenger window.This class again access the server
    for collecting the IDs of the online persons.But this statement which reads from the server causes an exception in the program.If we invoke the second class independently(ie not from 1st class) then there is no problem & the required data is read from the server.Can anyone please help me in getting this program right.I'm working on a p4 machine with JDK1.4.
    The Exceptions caused are given below
    java.net.SocketException: Connection reset by peer: Connection reset by peer
    at java.net.SocketInputStream.SocketRead0(Native Method)
    at java.net.SocketInputStream.read(SocketInputStream.java:119)
         at java.io.InputStreamReader$CharsetFiller.readBytes(InputStreanReader.java :339)
         at java.io.InputStreamReader$CharsetFiller.fill(InputStreamReader.java:374)
         at java.io.InputStreamReader.read(InputStreamReader.java:511)
         at java.io.BufferedReader.fill(BufferedReader.java:139)
         at java.io.BufferedReader.readLine(BufferedReader.java:299)
         at java.io.BufferedReader.readLine(BufferedReader.java:362)
         at Login.LoginData(Login.java:330)
         at Login.test(Login.java:155)
         at Login$Buttonhandler.actionPerformed(Login.java:138)
         at javax.swing.AbstractButton.fireActionPerformed(AbstractButton.java:1722)
         at javax.swing.AbstractButton$ForwardActionEvents.actionPerformed(AbstractButton.java:17775)
         at javax.swing.DefaultButtonModel.fireActionPerformed(DefaultButtonModel.java:4141)
         at javax.swing.DefaultButtonModel.setPressed(DefaultButtonModel.java:253)
         at javax.swing.plaf.basic.BasicButtonListener.mouseReleased(BasicButtonListener.java:261)
         at java.awt.Component.processMouseEvent(Component.java:4906)
         at java.awt.Component.processEvent(component.java:4732)
         at java.awt.Container.processEvent(Container.java:1337)
         at java.awt.component.dispatchEventImpl(Component.java:3476)
         at java.awt.Container.dispatchEventImpl(Container.java:1399)
         at java.awt.Component.dispatchEvent(Component.java:3343)
         at java.awt.LightweightDispatcher.retargetMouseEvent(Container.java:3302)
         at java.awt.LightweightDispatcher.processMouseEvent(Container.java:3014)
         at java.awt.LightweightDispatcher.dispatchEvent(Container.java:2967)
         at java.awt.Container.dispatchEventImpl(Container.java:1373)
         at java.awt.window.dispatchEventImpl(Window.java:1459)
         at java.awt.Component.dispatchEvent(Component.java:3343)
         at java.awt.EventQueue.dispatchEvent(EventQueue.java:439)
         at java.awt.EventDispatchThread.pumpOneEvent(EventDispatchThread.java:150)
         at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:136)
         at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:131)
         at java.awt.EventDispatchThread.run(EventDispatchThread.java:99)
         My program looks somewhat like this :
    1st class definition:
    public class Login extends Jframe// Login is the name of the first class;
    Socket connection;
    DataOutputStream outStream;
    BufferedReader inStream;
    Frame is set up here
    public class Buttonhandler implements ActionListener
    public void actionPerformed(ActionEvent e) {
    String comm = e.getActionCommand();
    if(comm.equals("ok")) {
    check=LoginCheck(ID,paswd);
    test();
    public void test() //checks whether the login is true
    if(check)
    new Messenger(ID);// the second class is invoked
    public boolean LoginCheck(String user,String passwd)
    //Enter the Server's IP & port below
    String destination="localhost";
    int port=1234;
    try
    connection=new Socket(destination,port);
    }catch (UnknownHostException ex){
    error("Unknown host");
    catch (IOException ex){
    ex.printStackTrace ();
    error("IO error creating socket ");
    try{
    inStream = new BufferedReader(new InputStreamReader(connection.getInputStream()));
    outStream=new DataOutputStream(connection.getOutputStream());
    }catch (IOException ex){
    error("IO error getting streams");
    ex.printStackTrace();
    System.out.println("connected to "+destination+" at port "+port+".");
    BufferedReader keyboardInput=new BufferedReader(new InputStreamReader(System.in));
    String receive=new String();
    try{
    receive=inStream.readLine();
    }catch(IOException ex){ error("Error reading from server");}
    if(receive.equals("Logintrue"))
    check=true;
    else
    check=false;
    try{
    inStream.close();
    outStream.close();
    connection.close();
    }catch (IOException ex){
    error("IO error closing socket");
    return(check);
    // second class is defined below
    public class Messenger
    Socket connect;
    DataOutputStream outStr;
    BufferedReader inStr;
    public static void main(String args[])
    { Messenger mes = new Messenger(args[0]);}
    Messenger(String strg)
    CreateWindow();
    setupEvents();
    LoginData(strg);
    fram.show();
    void setupEvents()
    fram.addWindowListener(new WindowHandler());
    login.addActionListener(new MenuItemHandler());
    quit.addActionListener(new MenuItemHandler());
    button.addActionListener(new Buttonhandle());
    public void LoginData(String name)
    //Enter the Server's IP & port below
    String dest="localhost";
    int port=1234;
    int r=0;
    String str[]=new String[40];
    try
    connect=new Socket(dest,port);
    }catch (UnknownHostException ex){
    error("Unknown host");
    catch (IOException ex){
    ex.printStackTrace ();
    error("IO error creating socket ");
    try{
    inStr = new BufferedReader(new InputStreamReader(connect.getInputStream()));
    outStr=new DataOutputStream(connect.getOutputStream());
    }catch (IOException ex){
    error("IO error getting streams");
    ex.printStackTrace();
    String codeln=new String("\n");
    try{
    outStr.flush();
    outStr.writeBytes("!@*&!@#$%^");//code for sending logged in users
    outStr.writeBytes(codeln);
    outStr.write(13);
    outStr.flush();
    String check="qkpltx";
    String receive=new String();
    try{
    while((receive=inStr.readLine())!=null) //the statement that causes the exception
    if(receive.equals(check))
    break;
    else
         str[r]=receive;
         r++;
    }catch(IOException ex){ex.printStackTrace();error("Error reading from socket");}
    catch(NullPointerException ex){ex.printStackTrace();}
    } catch (IOException ex){ex.printStackTrace();
    error("Error reading from keyboard or socket ");
    try{
    inStr.close();
    outStr.close();
    connect.close();
    }catch (IOException ex){
    error("IO error closing socket");
    for(int l=0,k=1;l<r;l=l+2,k++)
    if(!(str[l].equals(name)))
    stud[k]=" "+str[l];
    else
    k--;
    public class Buttonhandle implements ActionListener
    public void actionPerformed(ActionEvent e) {
    //chat with the selected user;
    public class MenuItemHandler implements ActionListener
    public void actionPerformed(ActionEvent e)
    String cmd=e.getActionCommand();
    if(cmd.equals("Disconnect"))
    //Disconnect from the server
    else if(cmd.equals("Change User"))
         //Disconnect from the server & call the login window
    else if(cmd.equals("View Connection Details"))
    //show connection details;
    public class WindowHandler extends WindowAdapter
    public void windowClosing(WindowEvent e){
    //Disconnect from server & then exit;
    System.exit(0);}
    I�ll be very thankful if anyone corrects the mistake for me.Please help.

    You're connecting to the server twice. After you've successfully logged in, pass the Socket to the Messenger class.
    public class Messenger {
        Socket connect;
        public static void main(String args[]) {
            Messenger mes = new Messenger(args[0]);
        Messenger(Socket s, String strg) {
            this.connect = s;
            CreateWindow();
            setupEvents();
            LoginData(strg);
            fram.show();
    }

  • Problem with socket connection

    have my gps reciver connected to the usb port - i have a daemon gpsd running which makes data available on tcp port 2947 for querying. when i do telnet, it gives proper data.
    but when i open a socket connection using java, it does not print anything as output. actually telnet asks for an escape charatcer so i am sending "r" initially to the server but still the program does not print anything as output.
    here is my java code -
    import java.io.*;
    import java.net.Socket;
    public class test2
    public static void main(String[] args)
    try
    Socket s = new Socket("localhost",2947);
    PrintWriter out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(
    s.getOutputStream())),true);
    out.println("r");
    BufferedReader in = new BufferedReader(new InputStreamReader(s.getInputStream()));
    String line;
    while(true)
    line = in.readLine();
    System.out.println(line);
    catch (Exception e)
    or sometimes it even shows error as
    Exception in thread "main" java.net.SocketException: Invalid argument or cannot assign requested address
    at java.net.PlainSocketImpl.socketConnect(Native Method)
    and this is the output which i get on telnet -
    ot@localhost ~]# telnet localhost 2947
    Trying 127.0.0.1...
    Connected to localhost.
    Escape character is '^]'.
    r
    GPSD,R=1
    $GPRMC,000212,V,18000.0000,N,00000.0000,W,0.0000,180.000,101102,,*1A
    $GPGSA,A,1,,,,,,,,,,,,,,,,*32
    $PGRME,400.00,0.00,0.00*7B
    $GPRMC,000213,V,18000.0000,N,00000.0000,W,0.0000,180.000,101102,,*1B
    $GPGSA,A,1,,,,,,,,,,,,,,,,*32
    $PGRME,400.00,0.00,0.00*7B
    $GPRMC,000214,V,18000.0000,N,00000.0000,W,0.0000,180.000,101102,,*1C
    $GPGSA,A,1,,,,,,,,,,,,,,,,*32

    Actually the problem does not seem to be in the code because i tried some basic client server programs (without any gpsd etc in picture) and even they are not working in linux though they work perfectly in windows (on the same machine). In linux it shows exception
    My socket programs dont work in linux it shows error -
    ot@localhost winc]# java parser
    Exception in thread "main" java.net.SocketException: Invalid argument or cannot assign requested address
    at java.net.PlainSocketImpl.socketConnect(Native Method)
    at java.net.PlainSocketImpl.doConnect(PlainSocketImpl.java:305)
    at java.net.PlainSocketImpl.connectToAddress(PlainSocketImpl.java:171)
    at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:158)
    at java.net.Socket.connect(Socket.java:452)
    at java.net.Socket.connect(Socket.java:402)
    at java.net.Socket.<init>(Socket.java:309)
    at java.net.Socket.<init>(Socket.java:124)
    at parser.main(parser.java:10)
    i have removed the firewall settings etc and it still doesnot work in linux
    what could be the cause for this?
    Sowmya

  • Problem with socket connection through Java Embedding...

    We are trying to create a simple socket connection to a socket server through BPEL PM using the Java Embedding component.
    BPEL Process : Client makes an asynchronous request. Passes an input variable. The input variable is sent to the Server Program through a socket connection through the Java embedding component.
    Server: We are running a simple Socket Server program from command prompt.
    The code below works fine as long as we do not try to receive a response from the server (Commented Code).
    If we uncomment the code and try to receive a response, it refuses to create an instance for the BPEL Process. And sometimes restarts the BPEL Server.
    Client Code:
    String msg="NONE";
    try{
    org.w3c.dom.Element input = (org.w3c.dom.Element) getVariableData("inputVariable","payload","/client:clientProcessRequest/client:input");
    msg = input.getNodeValue();
    Socket clientsoc=new Socket("ServerIP",1000);
    PrintWriter out1=new PrintWriter(clientsoc.getOutputStream());
    out1.write(msg);
    out1.flush();
    BufferedReader cin1=new BufferedReader(new InputStreamReader(clientsoc.getInputStream()));
    msg=cin1.readLine();
    setVariableData("outputVariable","payload","/client:result",new String(msg));
    clientsoc.close();
    catch(UnknownHostException e)
    System.err.println("Don't know about host: dev.");
    System.exit(1);
    catch (IOException e)
    System.err.println("Couldn't get I/O for "+ "the connection to: dev.");
    System.exit(1);
    }

    Repost

  • How to make a socket connection timeout infinity in Servlet doPost method.

    I want to redirect my System.out to a file on a remote server (running Apache Web Server and Apache Tomcat). For which I have created a file upload servlet.
    The connection is established only once with the servlet and the System.out is redirected to it. Everything goes fine if i keep sending data every 10 second.
    But it is required that the data can be sent to the servlet even after 1 or 2 days. The connection should remain open. I am getting java.net.SocketTimeoutException: Read timed out Exception as the socket timeout occurs.
    Can anyone guide me how to change the default timeout of the socket connection in my servlet class.
    Following is the coding to establish a connection with the Servlet.
    URL servletURL = new URL(mURL.getProtocol(), mURL.getHost(), port, getFileUploadServletName() );
    URLConnection mCon = servletURL.openConnection();
    mCon.setDoInput(true);
    mCon.setDoOutput(true);
    mCon.setUseCaches(false);
    mCon.setRequestProperty("Content-Type", "multipart/form-data");
    In the Servlet Code I am just trying to read the input from the in that is the input stream.
    public void doPost(HttpServletRequest req, HttpServletResponse res)
    throws ServletException, IOException
    BufferedInputStream in = new BufferedInputStream(req.getInputStream());
    byte [] content = new byte[1024];
    do
    read = in.read(content, 0, content.length);
    if (read > 0)
    out.write(content, 0, read);
    I have redirected the System.out to the required position.
    System.setOut(........);
    Can anyone guide me how to change the default timeout of the socket connection in my servlet class.

    I am aware of the setKeepAlive() method, but this can only used with the sockets. Here i am inside a servlet, have access to HTTPServletRequest and HTTPServletResponse and I don't know how to get access to the underlying sockets as the socket handling will be handled by the tomcat itself. If I am right there will be method in the apache tomcat 6.0.x to set this property. But till now I am not getting it.

  • Multiple clients on socket connection

    Hi!
    I understand that it is possible that multiple clients listen to one server (on the same port) and even write to it (then it should be a multi-threaded server).
    But i would like to refuse connectios, if one client is connected. How can I do that?
    In my case I have a (single threaded) server. Now one clients connects. The server waits to receive data from the client and answers, without ever closing the port. that works.
    Now if I connect with a second client, the openicng of the socket in the second client works fine, although the server does not seem to notice the second client. Communication is not possible between the server and the second client, and the server doesn't answer to the first client anymore, although he receives data from it.
    So, since the server does not seem to notice the second client (does not accept the connection) and I don't get an exception at the second client, what can I do?
    Thank you for your help!
    concerned Code (if you want to take a look at it):
    CLIENT:
    socket = new Socket(hostname, echo_port);
    SERVER:
    try
    ServerSocket waitingsocket = new ServerSocket(echo_port);
    try
         socket= waitingsocket.accept();
         System.out.println("Client connected");
         ReaderThread reader = new ReaderThread( this, socket );
         reader.start();          
    catch (Exception e)
    READER:
    public void run()
         while (true)
              try {
                   int bytesRead = inStream.read(inputBuffer,
                   0, inputBuffer.length);
                   readCallback.tcpUpdate(inputBuffer,bytesRead);
              catch (Exception oops)
                   readCallback.tcpUpdate(null,-1);
              

    Just to make sure this is clear: You can NOT have multiple clients on a given socket connection. You CAN have multiple clients connected to a particular port on a given server, but each client will be communicating with the server through a different of socket.
    The usual approach here is to set up a listening ServerSocket on the desired port, call accept() on it, then process the communication from the returned Socket object. This is usually done by spawning a new thread and allowing it to handle the socket communication, while the ServerSocket loops around to another accept() for the next communication.
    Here's an excellent intro to the concepts (the code is really ugly and poorly implemented, but it does a good job of explaining the overall concept). I used this as a starting point, and now (after a whole lot of development) have a pretty sweet extensible web server class that handles template expansion, etc... (I use this as a quick and dirty UI for some of my apps, instead of requiring the user to install a JSP container):
    http://developer.java.sun.com/developer/technicalArticles/Networking/Webserver/
    - K

  • How can i create a socket connection through an http proxy

    i'm trying to make a socket connection send an email - i have code that works when you don't have to go through a proxy server but i can't make it pass the proxy server.
    import java.net.*;
    import java.io.*;
    import java.util.*;
    public class Mail
    public String to_address = "[email protected]";
    public String from_address = "[email protected]";
    public String sendSub = "HeHeHe";
    public String sendBody = "hehehe - it worked";
    // This is created to allow data to be read in by the keyboard.
    BufferedReader in = new BufferedReader(
    new InputStreamReader(System.in));
         private void Mail(String to_address, // recipient's addresses
    String from_address, // sender's address
    String sendSub, // subject
    String sendBody) // Message
                   throws IOException, ProtocolException,      UnknownHostException {
         Socket socket;                // creates a Socket named socket
         PrintStream out;               // stream to write to socket
         String host = "imap.btopenworld.com";          // identification of the mail server host
    // creates a new socket for connection to the mail server
    // as well as two variables for the read and write streams
         socket = new Socket(host, 25); // opens socket to host on port 25 (SMTP port)
         out = new PrintStream(socket.getOutputStream());
    // read the initial message
         in.readLine();
    // Dialog with the mail server
    // send HELO to SMTP server HELO command is given by a connecting SMTP host
         out.println( "HELO " + host );
         out.flush() ;
         in.readLine();
    // Once we are connected to the mail server we start sending the email...
    // send "from"
         out.println( "MAIL FROM: " + from_address );
         out.flush() ;
         in.readLine();
    // send "to"
         out.println( "RCPT TO: " + to_address );
         out.flush() ;
         in.readLine();
    // prepare the mailserver to receive the data
         out.println( "DATA" );
         out.flush() ;
         in.readLine();
    // Send actual email
         out.println("From: " + from_address);
         out.println("To: " + to_address);
         out.println( "Subject: " + sendSub + "\n" );
         out.flush() ;
         out.println("");
         out.println( sendBody ) ;
         out.println(".") ; // standard to determine end-of-body
         out.flush() ;
         in.readLine();
    //Quit and closes socket
         out.println("QUIT");
         out.flush();
         in.close() ;
         socket.close() ;
         return ;
    public static void main (String [] args) throws IOException
    Mail themail = new Mail();
    }

    i've tried that but it doesn't seem to do nething - this is how i implemented it...
    import java.net.*;
    import java.io.*;
    import java.util.*;
    public class Mail
    public String to_address = "[email protected]";
    public String from_address = "[email protected]";
    public String sendSub = "HeHeHe";
    public String sendBody = "hehehe - it worked";
    // This is created to allow data to be read in by the keyboard.
    BufferedReader in = new BufferedReader(
    new InputStreamReader(System.in));
         private void Mail(String to_address, // recipient's addresses
    String from_address, // sender's address
    String sendSub, // subject
    String sendBody) // Message
                   throws IOException, ProtocolException,      UnknownHostException {
         Socket socket;                // creates a Socket named socket
         PrintStream out;               // stream to write to socket
         String host = "imap.btopenworld.com";          // identification of the mail server host
    // creates a new socket for connection to the mail server
    // as well as two variables for the read and write streams
         socket = new Socket(host, 25); // opens socket to host on port 25 (SMTP port)
         out = new PrintStream(socket.getOutputStream());
    // read the initial message
         in.readLine();
    System.getProperties().put( "proxySet", "true" );
              System.getProperties().put( "proxyHost", "144.124.16.28" );
              System.getProperties().put( "proxyPort", "8080" );
    // Dialog with the mail server
    // send HELO to SMTP server HELO command is given by a connecting SMTP host
         out.println( "HELO " + host );
         out.flush() ;
         in.readLine();
    // Once we are connected to the mail server we start sending the email...
    // send "from"
         out.println( "MAIL FROM: " + from_address );
         out.flush() ;
         in.readLine();
    // send "to"
         out.println( "RCPT TO: " + to_address );
         out.flush() ;
         in.readLine();
    // prepare the mailserver to receive the data
         out.println( "DATA" );
         out.flush() ;
         in.readLine();
    // Send actual email
         out.println("From: " + from_address);
         out.println("To: " + to_address);
         out.println( "Subject: " + sendSub + "\n" );
         out.flush() ;
         out.println("");
         out.println( sendBody ) ;
         out.println(".") ; // standard to determine end-of-body
         out.flush() ;
         in.readLine();
    //Quit and closes socket
         out.println("QUIT");
         out.flush();
         in.close() ;
         socket.close() ;
         return ;
    public static void main (String [] args) throws IOException
    Mail themail = new Mail();
    }

  • Connect Flash to Serial Port with Local Socket Connection

    Hey all,
    So, I am trying to connect a Flash movie to a serial port
    and have it react to the input coming in. Of course, Flash does not
    have this capability built in, so I need a workaround. I also
    program in Director, and there are easier ways to deal with this
    there, but since there hasn't been an update in years, and for
    other technical reasons, I would like to use a pure Flash program.
    I also need to take advantage of some of the new hardware
    acceleration improvements and horizontal sync issues that come with
    running the Flash player full screen. So, there are some tools out
    there that will let me stream the input from the serial port to a
    web address. I figure I could use the local address and assign a
    port number, then use Flash to create a local socket connection. I
    am having issues opening ports on my computer, and a few other
    things, but in theory, I think it should work. I know that I won't
    get all the answers here, but if anyone has done anything of the
    sort, or might know of some similar projects, it would really help.
    I am more of a Director/Flash programmer, and not so much one on
    the system level. So, opening local sockets, etc, while I am sure I
    can figure it out, is still a bit beyond me. Thanks all!
    - Bruce

    You may want to look into flash remoting, which would allow
    you to push content to the flash movie. You could then write a
    proxy between the source of your stream and flash the remoting
    server.

  • TCP Socket connection in CLOSE_WAIT status and not getting closed

    I am facing an issue with the TCP socket connections not getting closed and they are in CLOSE_WAIT status for ever.
    As a part of batch process in our application, emails are sent with 4 embedded images. These images are downloaded from 3rd party site with IP say "UUU.XXX.YYY.ZZZ"
    The images are embedded to email as follows
    1. An URL object is created with the site url.
    URL urlPhoto = new
    URL("http://UUU.XXX.YYY.ZZZ/email/photos.jpg");
    2.     The image cid is created with the URL object and the image name
    HtmlEmail htmlEmail = new HtmlEmail();
    String cid1 = htmlEmail.embed(urlPhoto,
    "photo.jpg");
    3.     The image cid is added to the email template by replacing the ${cid1} and the email is sent.
    <td valign="top">
                   <img src="cid:${cid1}" width="279" height="274">
              </td>
    When a mail is sent, 4 new TCP connections are opened and are put in CLOSE_WAIT status for ever. For every mail sent 4 new connections are opened. In UNIX there is an upper limit on the number of open file handles (defaults to 1024) at any point of time. The open TCP connection has the underlying socket in CLOSE_WAIT status and is not getting closed at all. When the upper limit (1024) is reached the batch process is throwing the following exception and terminates.
    Caused by: com.inet.tds.ap: java.net.SocketExceptionjava.net.SocketException: Too many open files
    at com.inet.tds.am.a(Unknown Source)
    at com.inet.tds.TdsDriver.a(Unknown Source)
    at com.inet.tds.TdsDriver.connect(Unknown Source)
    at java.sql.DriverManager.getConnection(DriverManager.java:525)
    at java.sql.DriverManager.getConnection(DriverManager.java:171)
    at com.hcomemea.batchprocess.dataaccess.database.BaseJdbcDao.openConnection(BaseJdbcDao.java:106)
    ... 12 more
    When I run the command lsof in UNIX which list the open file handles in the system
    $ /usr/sbin/lsof -p 22933 -i | grep CLOSE_WAIT
    java 22933 build_master 297u IPv6 129841943 TCP integration.com:47929->UUU.XXX.YYY.ZZZ:http (CLOSE_WAIT)
    java 22933 build_master 298u IPv6 129841947 TCP integration.com:47933->UUU.XXX.YYY.ZZZ:http (CLOSE_WAIT)
    java 22933 build_master 299u IPv6 129841950 TCP integration.com:47936->UUU.XXX.YYY.ZZZ:http (CLOSE_WAIT)
    java 22933 build_master 300u IPv6 129841970 TCP integration.com:47952->UUU.XXX.YYY.ZZZ:http (CLOSE_WAIT)
    ���list of 935 connections similarly�
    I tried 2 solutions
    1. Got the HttpURLConnection from the URL object and invoked disconnect method on the same. But it doesn�t work.
    2. Ran the batch process java program with the parameter �Dhttp.keepAlive=false to close the underlying connection but didn�t help.
    I need the underlying sockets to be closed and not put in CLOSE_WAIT status after sending the mail.
    Is it the problem with the embed method of HtmlEmail object not closing the underlying socket connection.
    If anyone has faced this issue before, kindly let me know the possible solutions for the same ASAP.
    Thank you,
    Ramesh G

    This sounds more like a problem due to connection pooling at middle tier/application server.
    If that has been ruled out, then you might to enable DCD or set expiry time on the server.

  • How do I transfer files verbatim across a socket connection?

    So, I've got this socket connection running between two computers. I want one computer to take a file (C:\SourceFile.doc for example) and transfer it verbatim over an Internet connection to another computer (C:\DestFile.doc for example). By verbatim, I mean bit for bit, no changes to the format. It would seem that a filereader/filewriter system would work, and it does fine for .txt or plain files, but if I try to do something fancy, like a Microsoft word document (.doc) it doesn't work. Specifically, it saves a bunch of garbage at the begging and end of the file. How do I correct this?
    From my file transmitter:
    out.println("Prepare for Text File");
    FileReader localin = new FileReader(file);
    int l=0;
    while((l=localin.read())!=-1)
         //System.out.print((char)l);
         out.print((char)l);
    localin.close();
    out.println("End Of File");
    From my file reciever
    if(line.equals("Prepare for Text File"))
         System.out.println("ready for text");               if(fileChooser.showSaveDialog(RadioComReciever.this)==JFileChooser.APPROVE_OPTION)
    File localFile=fileChooser.getSelectedFile();
              FileWriter localout = new FileWriter(localFile);
              line=in.readLine();
              while(!line.equals("End Of File"))
                   for(int i=0;i<line.length();i++)
                   {                                                                 localout.write((byte)line.charAt(i));
                   localout.write('\n');
                   System.out.println();
                   line=in.readLine();
              localout.close();
    Thanks for any help!

    But my program is already accessing text from a
    socket connection. Is there a way to transfer things
    over sockets other than text?Yes. Everything that goes over a socket connection is bytes. Certainly you can transfer text, because it can be represented in bytes, but not all files are text. So just send the bytes as is.
    Don't get me wrong, I'm thankful for you help, I just
    thought scokets mostly transfered just text. Am I
    wrong?I don't have any statistics on how much Internet traffic is text. But 100% of it is bytes. Just send the bytes as is.
    And is it just me, or is the documentation on File
    I/O provided by Sun somewhat lacking?It isn't the job of the documentation to explain basic Java concepts like the difference between byte and char. That's the job of the tutorials. Like the Java I/O tutorial.

Maybe you are looking for

  • I'm launching Adobe Media Encoder in Windows 7 to convert a mov to fla. Msg says it can not import

    I'm launching Adobe Media Encoder via Flash Import Video in CS5.5 in Windows 7. The message says "The file xxxx.mov could not be imported: Could not read from source. Please check the settings and try again"  What do I need to do? Thanks

  • Secondary cost from WBS to AUC

    Hi All, I am facing a problem in posting secondary costs from WBS to AUC. In Project systems they are considering secondary costs from the activities in the network. i settled the cost from network to WBS. and when i tried to settle From wbs to AUC s

  • Virtual Wireless LAN Controller and 1602E: No SSID

    Hello, I am trying to troubleshoot a customer's issue remotely.  They have vWLC 7.4, and a 1602E AP, running the 7.4 LWAPP image, successfully joined. Whatever is tried, the SSID configuration is not pushed to the AP.  Other configuration changes get

  • RAW files dark green

    After import, when I select a RAW file, it turns to a dark green hue. The following message occurs in the adjustments panel: "This photo was adjusted using an earlier version of Apple's RAW processing." Clicking on "Reprocess" does nothing. The corre

  • Regarding rman user session

    hi all, i need to create a trigger for tracing a particular user session or rman session so that only one trace file is used throughout, regardless of there number of logins or logoff thanks