Help in keeping a Persistent Socket connection

Hello All,
Pardon me, this is a silly question.. I have a Client who is using socket connection to connect to a server.. Currently the client is not maintaining a persistent connection. IT connects to t he server ,sends & receives messages from the server and then closes the connection. How do I keep the Socket connection alive so I can get the messages sent from the server asynchronously ???
thanks for your time

Thanks for your reply. Can I use thread to keep the connection alive.??? If so , It would be really helpful if U can show me a sample code......
Below is my piece of code...
try{
socket_Client = new Socket(name_server,portNumber);
InputStream input = socket_Client.getInputStream();
InputStreamReader in2 = new InputStreamReader(input);
BufferedReader in = new BufferedReader(in2);
getMessages(in); //this method gets the messages from the server
} catch ( Exception e)
} finally {
socket_Client.close()
thanks again

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.

  • Persistent socket connection - socket write error

    I'm connecting to a server using sockets. My application acts like a client, sending requests, and also like a server, listenning for notifications. I was using a client socket for the first task (send a message when required) and a server socket for the second (permanently listen for incoming messages). This needs to be some kind of persistent connection.
    It happens now I'm required to send and receive using the same port. The only way I found to do this is to have a single socket (client) bound to a certain port. It connects to the server and one thread keeps listenning for incoming messages (by reading the input stream) while another process is launched whenever I need to send a message (by writing to the socket's output stream). The socket is created only once (when the application starts) and its output/input streams reused whenever needed.
    This works well for a while. However, when I try to send a message after some idle time (lets say 20 minutes) strange things happen. The first attempt to send a message returns success (although nothing is actually received by the server). The second attempt returns java.net.SocketException: Software caused connection abort: socket write error. I don't understand this behaviour. Can there be a timeout? I only write to the socket after testing if it's connected.. So why is this failing? Also, any other ideas on how to send and receive using the same port? A different and better approach maybe..
    Thanks in advance

    Socket.isConnected just tells you whether you have personally called Socket.connect() or new Socket(host, port,...). It doesn't tell you anything about the state of the connection.
    You should certainly issue periodic application 'pings' at suitable intervals, and many application protocols do this. For example, Java RMI reuses connections that are less than 15 seconds old but only if they pass a ping test.
    In general however you can't insist on a persistent connection over TCP/IP, especially if you have this kind of hardware in the circuit. What you can do is recognize when the connection has been lost and form a new one. The network is going to fail somewhere some time and your program has to be robust against that.

  • Persistent Socket Connection

    Hi
    We have implemented a composite, where we are connecting to a systm using socket adapter. After moving to production we realize that our application is sending CLOSE_WAIT signal in the socket in predetermined interval, but the client application is not able to close the socket immediately. They are saying that their application is tuned to work with dedicated TCP/IP connections.
    We were wondering if there any way to setup dedicated connections, i.e., not to close the socket. We have turned on the keep-alive parameter in socket adapter. We are looking some option at OS level (Sloaris in our case) like tcp_time_wait_interval. But I think this will impact globally which we don't want for obvious reasons.
    Regards

    Hi All,
    Interesting result. After we have turned off keepAlive property, we can see the number CLOSE_WAIT sockets have reduced (almost zero), and now we can see TIME_WAIT sockets for sometime, which is okay.
    I guess the back end application had some problem with socket timeout settings.
    Regards

  • Keep opened socket connection?

    Hi,
    My Java application communicates with server on average every 3 seconds. I wonder if it is a good idea to keep an opened socket connection to the server and don't open new connection for each request. The problem with this is that if in the meantime is connection aborted, java.net.SocketException is throwned.
    What do you think about keeping opened connection? Is appropriate to work with opened connections or to open new connection for each new request? How do you solve in your applications situation when communication is irregular but frequent.
    Thanks.

    I had one more question on this topic relating to capture and processing exceptions. Communication between client and server I accomplish wit these three classes:
    - ClientRequest - represents client request to the server
    - Communication - gets ClientRequest and socket connection to the server and sends the request to the server
    - ServerResponse - represents response returned from the server
    Now If Communication class gets dead connection it can't work and throws an exception. We discussed that I should find out the situation and suitably respond to this situation.
    My question is whether the method for reconnection should call:
    a) Communication class
    b) class that uses the Communication class?
    c) somebody else (?)
    In case a) there is an advantage that all is in one place and Communication class user does not have to worry about anything beause class will try reconnect itself (if second attempt fails, method throws another exception). The advantage of b) is that the user needs, he can respond to this situation and do some another action.
    Thanks.

  • Is it wise to keep the socket connection open?

    When u have a bunch of HTTP requests coming in to a listener server socket, would it be safe to keep my JAVA socket connection open with KeepAlive or simply open/close at will? I thought of a connection of sockets as well. Thoughts? thx!

    It depends which socket your talking about
    The serversocket you want to always be open and listened to
    the sockets it spawns you should close when you've finished the transaction

  • Servlets or EJB for Persistent external socket connections

    We have a Servlet that establishes a socket connection to another
    external server and sends and receives messages. We have the Servlet defined as pre-loaded when JRun starts.
    When JRun is started, the Servlet is started and connection is
    established with the external server. The problem is when a new message is being sent, the Servlet is instantiate again and the connection is stopped and restarted. We do a forward request from another Servlet to this.
    Am I totally misunderstanding Servlets because reading articles
    and books seems to indicate that I should create an EJB instead of a
    Servlet if you want a persistent connection.
    Thanks in advance for your help.

    I assume then that your connection to the external server is achieved in the "init" method of your servlet. Therefore every time the servlet container is called upon to accesss your servlet, it instantiates it - thus a new connection will be being made each time.
    I would take out the connection properties from the init method. I.e. you only want it to happen once.
    T

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

  • HELP I keep getting an error message on my IPHONE 4 that says Unable to connect to Cellular Data. How do I fix this?

    HELP I keep getting an error message on my IPHONE 4 that says Unable to connect to Cellular Data and I have tried to reset network settings and factory reset but nothing helping so far. Took it to Verizon and they couldn't fix it either, said it's a problem with the phone itself and to contact Apple. My warranty is expired so Apple isn't much help either. How do I fix this? I have a data package so confused and I have had my phone for over a year but never had this issue before.

    I am getting this message also.... mine cant update too...

  • Socket Connection - Character Set - Help

    Hello:
    I am creating a socket using UTL_TCP package. After making a successful connection, I have to send data in ISO-8859 format. The message should look something like this.
    STX followed by data in ascii followed by ETX.
    STX and ETX are ascii for 2 and 3.
    I have the data in STRING. example 'DOWNLAOD ME TO THE SERVER'. This string is currently in VARCHAR2 variable.
    I would like to know how can I convert the above data to ASCII string and then prefix it with STX and suffix with ETX before I send it down the socket. I think I have to use utl_encode package but am not sure where to start.
    Please help.
    Thanks.

    Do not understand your problem. It seems to me that you simply need to create a varchar2 string that contains the ASCII text you want to transmit via TCP using the socket connection you have creared, using the API call UTL_TCP.WRITE_LINE (write string without a TCP linefeed char) or UTL_TCP.WRITE_LINE (with linefeed).

  • I have installed Adobe digital additions and have tried to aurthorize but keep getting error message "Connection error" . The internet connection is working and I do have an Adobe ID can you help please

    I have installed Adobe digital additions and have tried to authorize but keep getting error message "Connection error" . The internet connection is working and I do have an Adobe ID can you help please.
    I have been using Adobe reader for PC to download my eBooks but the eBook Vendor has switch to Digital Addition,

    this is from sjpt,
    Try completely removing any authorization using ctrl-shift-D to ADE (cmd-shift-D if on Mac).
    Restart ADE, and then reauthorize with your Adobe ID.

  • Trying to download songs from Itunes store. Keeps saying unable to connect. I have tried from store on computer and on phone. Please help i have weddings to do and need these songs!!!!!!!!!!!!!!!

    Trying to download songs from Itunes store. Keeps saying unable to connect. I have tried from store on computer and on phone. Please help i have weddings to do and need these songs!!!!!!!!!!!!!!!

    Hey everybody Amazon.com works perfectly and no problems so Bye, Bye Itunes fix your junk *** program and ****** customer service telling me it's my computer and connection. Oh is that also why my phone can't download them either on a seperate cell network. Nice try garbage In the time it took for them to run me around i downloaded the songs i needed via Amazon.

  • Premiere elements 13 keeps asking me to connect to internet to register the product but my internet is fine. I have gone through the forum to get help but nothing is OK....

    Premiere elements 13 keeps asking me to connect to internet to register the product but my internet is fine. I have gone through the forum to get help (validation of internet, validation of the ability to access secure servers, the validity of the ceritificate....) but nothing is working for me. Would someone have additional info. to handle this situation ? Thanks

    Jean Lucd86932678 to confirm you completed the steps listed in Sign in, activation, or connection errors | CS5.5 and later?  If so what specific error messages are you receiving?

  • Help with an exception when trying to establish a socket connection

    i am trying to make a chat (using an applet for the client).......
    it uses an simple socket connection between the server and clients.....when i connect the client to address 127.0.0.1 or localhost everything works fine, but when i try to connect the client to my DNS name or ip, i get an exception....the exception reads:
    java.security.AccessControlException: access denied (java.net.SocketPermission nextwave.dyndns.org resolve)
    at java.security.AccessControlContext.checkPermission(AccessControlContext.java:270)
    at java.security.AccessController.checkPermission(AccessController.java:401)
    at java.lang.SecurityManager.checkPermission(SecurityManager.java:542)
    at java.lang.SecurityManager.checkConnect(SecurityManager.java:1042)
    at java.net.InetAddress.getAllByName0(InetAddress.java:937)
    at java.net.InetAddress.getAllByName0(InetAddress.java:918)
    at java.net.InetAddress.getAllByName(InetAddress.java:912)
    at java.net.InetAddress.getByName(InetAddress.java:832)
    at java.net.InetSocketAddress.<init>(InetSocketAddress.java:109)
    at java.net.Socket.<init>(Socket.java:119)
    at Client.<init>(Client.java:42)
    at ClientApplet.init(ClientApplet.java:12)
    at sun.applet.AppletPanel.run(AppletPanel.java:347)
    at java.lang.Thread.run(Thread.java:536)
    what is this all about??????
    i'm not that fluent in java, or networking at that, but i'm sure there is something i can do to fix this......
    any help would be greatley appreciated.

    this is why i am not heart-broken that i will be going the other (executable jar) route.......the major deciding factor is the people who will be using this chat will most likley not be able to edit the policy file due to lack of knowledge, and probably won't want to take the time to try.....they would rather download a program, and double-click execute........
    i thank you for taking the time to help me......i have been reading through the posts in this forum, and am seeing it is a good place to get help, so i will be sticking around.....
    mahalo and happy java

  • I'm unable to open most of the websites. the message keeps displaying that the "connection is untrusted"...pls help fellas...thank you

    after trying out some add on's and even after disabling them, and even after reinstalling firefox afresh, i'm unable to open most of the websites(including gmail, hotmail, facebook etc).where as my other browsers works quite fine. the message keeps displaying that the "connection is untrusted"...pls help fellas...thank you

    See if this helps:
    http://www.techiecorner.com/1065/firefox-this-connection-is-untrusted/

Maybe you are looking for

  • In webdynpro ,Passing field symbols as values to class methods

    Hi Please tell me the ways of accessing database in webdynpro abap(not directly). I am calling Class method for accessing database. As currently I am directly accessing database in my webdynpro application. I have created a class and method for the s

  • Can't figure out how to turn the Sharing control back on in iTunes

    Recently, I have begun using Limewire to download music. A few days ago a message came up on my computer that said something like "The Sharing Control on your iTunes playlist has been turned off".I can't figure out how to turn it back on, and I have

  • Japanese character in Code Editor of "View" is shown as Question Marks

    Hi All, I have a probelm where I tried to create a view having decode function as shown below: decode(A.resource_process_name,         'ザイコ', 'Inventory',         'PP良後', 'Wafer BE',         'PP良前', 'Wafer FE',         'PP良済', 'Wafer',         'PP良引'

  • Weird Artifactin​g with Windows Live Messenger

    So, I noticed that I get some artifacting with Windows Live Messenger's notifications after restoring my W520 to its factory settings again. I got angry at it and restored it to factory settings again, and it is still present. Yes, I've tried updatin

  • SAP WM -Stock Placement

    Hi Two quries The scenario is -On receipt of stock need to first fill the Fixed bin in the Fixed storage type and if the capacity reached max in the fixed bin then the reserve bins in the reserve storage types are to be filled.Only one fixed bin is m