Socket connection validity

Hi,
I have connected my client to a server and did some operation and then left teh client for sometime. Now after sometime..I want to do some operation on teh same connection,but before that I want to check the validty of connection i.e whether the connection is still alive or not. Does Java has any API to check taht whether the connection is alive or not.
Or does someone knows how I send a keepalive packet from my application.

ok, this is my last attempt to tell you how it is....
you want to send some sort of test packet, if its ok, you continue to send your data. so heres what happens
pass...
client: send TCP test
server: ok
client: send data
fail...
client: send TCP test
server: nothing because the connection has failed
client: generates IOException because you tried to use a Socket thats no longer conected
client: create new connection
client: send data
why ever not
pass...
client: send data
fail...
client: send data
server: nothing because the connection has failed
client: generates IOException
client: create new connection
client: send data

Similar Messages

  • Urgent --- Persistent socket connection?

    Hi, I have a question about the persistency of a Java Socket connection. Is it a valid idea to keep a java socket open for a long time? If so, what special care do I need to take?
    My Java TCP/IP client runs as a NT service. It keeps getting input messages every few seconds, then send it thru a socket connection to a TCP/IP server. In order to avoid the overhead of opening and closing the socket every time the client gets a message to send, I want to keep the socket connection open and reuse it.
    I was able to send hundreds of messages thru this way, then after a while, for no apparent reason,
    the socket stops working, I typically get an exception like this:
    java.net.SocketException: Connection Shutdown: JVM_recv in socket input stream read
    at java.net.SocketInputStream.socketRead(Native Method)
    at java.net.SocketInputStream.read (SocketInputStream.java:90)
    at java.net.SocketInputStream.read (SocketInputStream.java:71)
    at java.io.InputStreamReader.fill (InputStreamReader.java:163)
    at java.io.InputStreamReader.read (InputStreamReader.java:239)
    at java.io.BufferedReader.fill (BufferedReader.java:137)
    at java.io.BufferedReader.readLine (BufferedReader.java, Compiled Code)
    at java.io.BufferedReader.readLine (BufferedReader.java:329)
    My programs runs on NT4.0, single-threaded. Any input would be greatly appreciated.

    Is it a valid idea to keep a java socket open for a long time? If so, what
    special care do I need to take?Depends.
    First why keep it open? Your messages only arrive every couple of seconds, does opening/closing the connection take longer than that?
    If you must then the complication you must deal with is that your code must deal with re-establishing the connection when it does fail. Opening/closing it every time avoids that issue. The connection will fail, because computers fail, networks fail and people make mistakes. Which doesn't mean that you shouldn't but merely that you should consider the implications of why you need to keep it open.

  • Sockets connection

    Can anybody help me how to connect Flash to a server Using Sockets connection using in AS3.

    Use following code UPDATED:
    try
    var mySocket:Socket = new Socket();
    var isConnected:Boolean = false;
    var portNumber:Number =8000; //Enter Port number you want to use instead of 8000;
    var IPAddress:String = "localhost"; //Enter server IP instead of localhost;
    //Valid range of port numbers is 1 to 65535
    if (portNumber >= 1 && portNumber <= 65535)
      //Create new socket.
      mySocket=new Socket  ;
      //Connect to host and port.
      mySocket.connect(IPAddress,portNumber);
      //Add listeners to socket to start communicating with the server.
      mySocket.addEventListener(IOErrorEvent.IO_ERROR,errorOccured);
      mySocket.addEventListener(SecurityErrorEvent.SECURITY_ERROR,errorOccured);
      mySocket.addEventListener(ProgressEvent.SOCKET_DATA,readFromServer);
      mySocket.addEventListener(Event.CONNECT,connectionEstablished);
    else
      //Show error message
      trace("Server is not reachable on port " + portNumber + ".");
      ExternalInterface.call("alert","Server is not reachable on port " + portNumber + ".");
    catch (e)
    //Show error message
    trace("Server is not reachable.");
    ExternalInterface.call("alert","Server is not reachable.");
    function readFromServer(evnt:ProgressEvent):void
    //Read message
    var str:String = mySocket.readUTFBytes(mySocket.bytesAvailable);
    //Remove line breaks.
    while (str.indexOf("\n") > -1)
      str = str.replace("\n","");
    while (str.indexOf("\r") > -1)
      str = str.replace("\r","");
    //Message from server received...
    trace(str);
    function writeToServer(toUserName:String, messageStr:String):void
    if (isConnected)
      var pushStr = "Message from Flash to server";
      mySocket.writeUTFBytes(pushStr);
      mySocket.flush();
    //This function is called when connection to server is successful.
    function connectionEstablished(evnt:Event)
    //Mark socket connection with the server as connected.
    isConnected = true;
    function errorOccured(evnt:Event)
    //Some error occured
    trace("Some error occured!");
    ExternalInterface.call("alert","Some error occured!");

  • Socket.connect

    I'm trying to write a client application that will connect to a server whenever it becomes available. There are some problems which I hope someone will be able to help, Below is a snippet of the code that makes the connection:
    while(alive){
    try{
    /* part 1*/
    Socket s = new Socket();
    s.setReuseAddress(true);
    s.bind(localAddress);
    /* end part 1*/
    s.connect(targetAddress);
    } catch (Exception e){}
    this seems to works fine. However when I place part 1 of the code outside the while loop. the connection will not be made if the server application is up after my connection thread has started running. Isnt Socket.connect suppose to block until a valid connection is made?
    Also when running my application (with the code above) over a long period of time, I get a OutOfMemoryException (native memory) when the server application is not present. Do I have to specify some other parameters for the JVM to release the native resources allocated for a socket construction or is this just a bug? I am running the application using java 1.6 on RHEL4 2.6.9-34.ELSMP.
    Thank you in advance.

    The thread is respawned when then server application
    drops thus yes the socket will only make one
    connection.Not if you move part 1 out of the loop.If you do that you will attempt multiple connections with the socket, which doesn't work.
    Shouldnt the thread block when .connect() fails?Why? Block doing what?
    Instead i'm getting a connection refused exception.What else should it do?
    No i did not close the socket when I get an exception.You should.
    Should the resources be reclaimed since
    the socket object would have gone out of scope?Eventually.
    I'm running my application on a system with multiple
    network cards thus i need to bind it to the intended
    address.Why? TCP/IP will find the best route if you don't get in its way. Why not let it?

  • Java Socket Connection Time out

    Goal*
    I want to check host/port availability of computers in our network (~100 computers) .. Just check if host is alive and if it has port 445 opened. I want to do this somehow in parallel, so the code execution is as quick as possible.
    My implementation*
    I do this by creating socket connection to the host. Something like this:
            Socket s = null;
            try {
                s = new Socket();
                InetSocketAddress socketAddress = new InetSocketAddress(ipAddress, 445);
                s.connect(socketAddress, 3000);
                if (s.isConnected()) {
                    // do something
            } catch (ConnectException ex) {
                //exception thrown
            } catch (IOException ex1) {
                //exception thrown
            } finally {
                try {
                    // close socket
                    s.close();
                } catch (IOException ex) {
                    Logger.getLogger(ComputerModel.class.getName()).log(Level.SEVERE, null, ex);
            }This code is executed in a loop, where a separate thread is created for every iteration = ~100 separate threads.
    Problem:*
    1.
    It seems to me, that first ~10-15 connections are created ok, but then my code reaches 'IOException' catch block for every subsequent itteration and ex.getMessage() returns "connection time out" (I try to use different timeout values in the 2nd parameter. Values from 3000 up to 20000).
    Is it valid to create 100 separate threads in a loop? Can't I make my NIC to bussy with this ??? What is the maximum ammount of threads, I can create? I did not use threads before, so I have no idea, if max values are near to 10, 100, 1000, or 10000 ..
    2.
    After my code is executed, I enter 'netstat -an' command in my command line and I get bunch of connections, which report status of SYN_SENT for several connections.
    TCP 10.20.11.140:4557 10.30.11.119:445 SYN_SENT
    TCP 10.20.11.140:4558 10.30.11.176:445 SYN_SENT
    TCP 10.20.11.140:4559 10.30.11.100:445 SYN_SENT
    TCP 10.20.11.140:4560 10.30.11.142:445 SYN_SENT
    TCP 10.20.11.140:4561 10.30.11.171:445 SYN_SENT
    TCP 10.20.11.140:4562 10.30.11.143:445 SYN_SENT
    TCP 10.20.11.140:4563 10.30.12.12:445 SYN_SENT
    TCP 10.20.11.140:4564 10.30.12.11:445 SYN_SENT
    TCP 10.20.11.140:4565 10.30.12.21:445 SYN_SENT
    TCP 10.20.11.140:4566 10.30.11.150:445 SYN_SENT
    I also feel, that my computer network response (e.g. firefox browsing) is a bit slower ..
    How shall I handle this problem properly?
    Thx in advance,
    Juraj

    kajbj wrote:
    tschodt wrote:
    kajbj wrote:
    The documentation for netstat explains what SYN_SENT is, but
    I don't know why you have them.The app has asked the TCP stack to transmit SYN
    the TCP stack is now waiting for SYN-ACK.
    If there is no host at that IP address or a host that drops connections (SYN packets) for TCP port 445
    there will never be a SYN-ACK.
    After a few minutes the TCP stack will time out the connection attempt.Yes, I was rather commenting on why his hosts aren't answering. I thought that his case was that all of them should answer :)Akkurat. I was answering more for clarification.
    Someone who does not know your posting history could easily assume you meant
    it was a mystery why netstat was showing SYN_SENT.
    And I figured it would not harm to hint that one possible reason would be that those machines are powered off (no host).

  • Socket connect slow in JDK 1.5?

    We recently began testing our Java Swing application with JDK 1.5, and we noticed that socket.connect()
    calls are taking several seconds to return, when before in 1.4 the calls returned immediately.
    Here is some sample code:
    Socket sock = new Socket();
    InetSocketAddress sockAddr = new InetSocketAddress(inAddress, portNum);
    sock.connect(sockAddr, 2000);
    What could be wrong? I've debugged the code and verified inAddress is an IP address,
    not a hostname.
    -Eric

    Here is the list of enhancements in JDK1.5.
    http://java.sun.com/j2se/1.5.0/docs/guide/net/enhancements-1.5.0.html
    I wonder if any of them are having some effect in the slow connection.
    There are some network properties that you can tweak with. Did you try them?
    Here is the list
    http://java.sun.com/j2se/1.5.0/docs/guide/net/properties.html

  • Is there any way to identify the particular socket connection is closed ?

    Is there any way to identify the particular socket connection is closed or not ?
    Any methods ???
    How can the program knows the connection is lost or some thing ...
    Is the socket throws some excpetions when there is no active connection ???
    namanc

    If you get an IOException when you try to use the socket, the connection was obviously closed.
    The correct way for an application to know if the socket was closed is:
    1) the server sends a message indicating that the socket should be closed
    2) the client closes the socket itself

  • 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

  • Problem with socket connection in midp 2.0

    hello everyone.
    I'm new one in j2me and I am learning socket connection in j2me. I'm using basic socket,datagram example wich is come with sun java wireless toolkit 2.5. for it i wrote small socket server program on c# and tested it example on my pc and its working fine. also socket server from another computer via internet working fine. But when i instal this socket example into my phone on nokia n78 (Also on nokia 5800) it's not working didn't connect to socket server.. On phone I'm using wi-fi internet. Can anybody help me with this problem? I hear it's need to modify manifest file and set appreciate pressions like this
    MIDlet-Permissions: javax.microedition.io.Connector.socket,javax.microedition.io.Connector.file.write,javax.microedition.io.Connector.ssl,javax.microedition.io.Connector.file.read,javax.microedition.io.Connector.http,javax.microedition.io.Connector.https
    is it true?
    can anybody suggest me how can i solve this problem?
    where can I read full information about socket connection specifiecs in j2me?
    Thanks.

    Maybe this can be helpful:
    [http://download-llnw.oracle.com/javame/config/cldc/ref-impl/midp2.0/jsr118/index.html]
    you can check there the Datagram interface anda DatagramConnection interface and learn a little about that.
    If the client example runs fine in the wireless toolkit emulator, it should run the same way in your phone; i suggest to try to catch some exception that maybe is hapenning and display it on a Alert screen, this in the phone.

  • 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 reuse my existing socket connection

    Hi,
    this might sound basic, it probably is:
    As part of my larger project, i have to send and recieve data to multiple socket connections.
    The thing that happens is that everytime i send data, it seems that java is creating a new stream or something (code is multithreaded)
    so as i send 4 items of data, a bit like a chat program sending 4 statements, it creates 4 different streams, instead of using the same stream. therefore when i close the connection, i get:
    java.net.SocketException: Connection reset 4 times.
    i know why.. its because i have added the:
    Socket socket=new Socket(host, port);
    BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
    PrintWriter out = new PrintWriter(new OutputStreamWriter(socket.getOutputStream()));
    bit in the same method with the
    out.println(THE DATA....);
    out.flush();
    The thing what i want to do is to create the connection one, and reuse the objects:
    out, in and socket
    to send / recieve the new data.
    please help me guys,
    thanks

    All the threads would be able to get the same reference to....
    class SocketWrapper {
         private final Object readLock = new Object();
         private final Object writeLock = new Object();
         // client side
        public SocketWrapper(String hostname, int port);
         // server side.
        public SocketWrapper(Socket);
         // send data
         public void send(Serializable object) throws IOException;
         // receive data. synchronized(writeLock);
         public Serializable getNext() throws IOException;
         // create a new socket as required, throw IllegalState if server side. synchronized(readLock)
         private void createNewSocket() throws IllegalStateException;
    }The send autoconnects as required. It then send on message/packet/object.
    The getNext autoconnects as required. It reads one message/packet/object and returns.
    This allows multiple threads to access the same socket. It allows data to be sent while a thread is blocking on a read. (Thus two locks)

  • 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();
    }

Maybe you are looking for

  • Single Sign-On (Portal to R/3 Backend)

    Hi all, Iu2019m trying to implement Single Sign On (SSO) between our SAP portal (front end) and SAP R/3 ECC 6.0 Backend.  Keep in mind this has nothing to do with Active Directory. I read posting after posting from this site and I canu2019t tell you

  • How can i sort the RowSet?

    I have the 2 (master and detail) entity objects, and corresponding 2 (master and detail) view objects. Then i've generated the entity object class for the master EO, this class has methods of getting/setting EO attributes, and method for getting a ro

  • TopLink ADF Faces Tutorial - Object Generation Error

    Hi, I'm trying to work through the tutorial "Build a Web Application with ADF Faces and Oracle TopLink" (http://www.oracle.com/technology/obe/obe1013jdev/masterdetailedit_adftoplink/endtoend_toplink_adffaces.htm#t2), but I am stuck at the last step o

  • G-Raid 2

    I am considering buying a G-Raid 2 to store media files. It will be used with a Power Mac G5. Questions: 1. If I buy a 500-gig drive (selling for about $399) and find I need more storage space, can I get a second 500-gig drive and double my storage?

  • X301 external monitor can't go above 1440x900 resolution.......help!

    I am running an x301 which has Intel GMA4500MHD graphics.  I am using Windows 7.  All drivers and BIOS have been updated to the latest. When I connect the x301 to my Vizio VF550M HDTV via a DisplayPort to HDMI adapter, I can only goto 1440x900.  This