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

Similar Messages

  • Separate jsp/servlets from EJBs for petstore

    By default, petstore deploy all the web apps and EJBs in one ear. I am trying to
    separate the JSP/servlets to deploy to diffent machine. I need to modify the client
    InitialContext to point to the remote server. I took a look at the source and
    there are many places using the default constructor of InitialContext to load
    the default URL. I wrote a jndi.properties file that has the correct url and put
    this to the classpath. I know this file needs to be put to the working directory,
    too. In case of pet store web application, what should be the working directory?
    Thanks, Cathy

    I'm also interested in running the Pet Store application server and the database
    (Oracle prefered) on different systems.
    Is this configurable during runtime or does it require code modification, compilation
    and deployment?
    Thanks,
    TL

  • How to set proxy for client-server socket connection?

    Hi,
    I'm using the code found on the following page to create a client (mobile) to server (pc) connection and send a text message.
    http://javafaq.nu/java-example-code-503.html
    This works with mobile operators without proxy, but does nothing when the operator uses a proxy. The question is, exactly how to set the proxy and port values for using that code.
    Any help is greatly appreciated, thanks,

    It's part of the cellular settings, and is usually set up by your 3G provider. You can't choose your own proxy server

  • Do we need ejb for persistance of obects

    hai ,
    I heard that hibernate can be used for persiatance of object .
    Which method is more efficient.
    regards

    Hi,
    Entity beans provide a lot of services for ex.
    1. Authentication & Authorization
    2. TX Management
    3. Resource management.
    4. Lifecycle managment by container
    5. Distributed computing environment etc. to name a few.
    There are advantages of using EJB as well as some disadvantages. However use of a particular technology such as EJB or Spring should be very carefully decided based purely on business needs.
    HTH
    VJ

  • Establishing a socket connection between a .swf file and a socket-test program (TCP/IP builder - Windows), in AS3.

    I have an issue with a college project I'm working on.
    Using Actionscript 3, I made a simple .swf program, an animated, interactive smiley, that 'reacts' to number inputs in a input-box.
    For the sake of the project, I now need to make the framework for establishing a socket connection with the smiley .swf, and another program.
    This is where I encounter issues. I have very little knowledge of AS3 programming, so I'm not certain how to establish the connection - what's required code-wise for it, that is.
    To test the connection, I'm attempting to use the "TCP/IP builder" program from windows, which lets me set up a server socket. I need to program the .swf file into a client - to recognize it, connect to it, then be able to receive data (so that the data can then be used to have the smiley 'react' to it - like how it does now with the input-box, only 'automatically' as it gets the data rather than by manual input).
    My attempts at coding it are as follows, using a tutorial (linked HERE):
    //SOCKET STUFF GOES HERE
        var socket:XMLSocket;        
        stage.addEventListener(MouseEvent.CLICK, doConnect); 
    // This one connects to local, port 9001, and applies event listeners
        function doConnect(evt:MouseEvent):void 
        stage.removeEventListener(MouseEvent.CLICK, doConnect); 
        socket = new XMLSocket("127.0.0.1", 9001);   
        socket.addEventListener(Event.CONNECT, onConnect); 
        socket.addEventListener(IOErrorEvent.IO_ERROR, onError); 
    // This traces the connection (lets us see it happened, or failed)
        function onConnect(evt:Event):void 
            trace("Connected"); 
            socket.removeEventListener(Event.CONNECT, onConnect); 
            socket.removeEventListener(IOErrorEvent.IO_ERROR, onError); 
            socket.addEventListener(DataEvent.DATA, onDataReceived); 
            socket.addEventListener(Event.CLOSE, onSocketClose);             
            stage.addEventListener(KeyboardEvent.KEY_UP, keyUp); 
        function onError(evt:IOErrorEvent):void 
            trace("Connect failed"); 
            socket.removeEventListener(Event.CONNECT, onConnect); 
            socket.removeEventListener(IOErrorEvent.IO_ERROR, onError); 
            stage.addEventListener(MouseEvent.CLICK, doConnect); 
    // Here, the flash tracks what keyboard button is pressed.
    // If 'q' is pressed, the connection ends.
            function keyUp(evt:KeyboardEvent):void 
            if (evt.keyCode == 81) // the key code for q is 81 
                socket.send("exit"); 
            else 
                socket.send(evt.keyCode); 
    // This one should handle the data we get from the server.
            function onDataReceived(evt:DataEvent):void 
            try { 
                trace("From Server:",  evt.data ); 
            catch (e:Error) { 
                trace('error'); 
        function onSocketClose(evt:Event):void 
            trace("Connection Closed"); 
            stage.removeEventListener(KeyboardEvent.KEY_UP, keyUp); 
            socket.removeEventListener(Event.CLOSE, onSocketClose); 
            socket.removeEventListener(DataEvent.DATA, onDataReceived);
    Trying to connect to the socket gives me either no result (other than a 'connection failed' message when I click the .swf), or the following error:
    Error #2044: Unhandled securityError:. text=Error #2048: Security sandbox violation: file:///C|/Users/Marko/Desktop/Završni/Flash%20documents/Smiley%5FTCP%5FIP%5Fv4.swf cannot load data from 127.0.0.1:9001.
        at Smiley_TCP_IP_v4_fla::MainTimeline/doConnect()[Smiley_TCP_IP_v4_fla.MainTimeline::frame1:12] 

    Tried adding that particular integer code, ended up with either errors ("use of unspecified variable" and "implicit coercion") , or no effect whatsoever (despite tracing it).
    Noticed as well that the earlier socket code had the following for byte reading:
    "sock.bytesAvailable > 0" (reads any positive number)
    ...rather than your new:
    "sock.bytesAvailable != 0" (reads any negative/positive number)
    Any difference as far as stability/avoiding bugs goes?
    So then, I tried something different: Have the program turn the "msg" string variable, into a "sentnumber" number variable. This seemed to work nicely, tracing a NaN for text (expected), or tracing the number of an actual number.
    I also did a few alterations to the input box - it now no longer needs the 'enter' key to do the calculation, it updates the animation after any key release.
    With all this considered and the requirements of the project, I now have a few goals I want to achieve for the client, in the following order of priority:
    1) Have the "sentnumber" number variable be recognized by the inputbox layer, so that it puts it into the input box. So in effect, it goes: Connect -> Send data that is number (NaN's ignored) -> number put into input box -> key press on client makes animation react. I optionally might need a way to limit the number of digits that the animation reacts to (right now it uses 1-3 digit numbers, so if I get sent a huge number, it might cause issues).
    - If the NaN can't be ignored (breaks the math/calculus code or some other crash), I need some way of 'restricting' the data it reads to not include NaN's that might be sent.
    - Or for simplicity, should I just detect the traced "NaN" output, reacting by setting the number variable to be "0" in such cases?
    2) After achieving 1), I'll need to have the process be automatic - not requiring a keyboard presses from the client, but happening instantly once the data is sent during a working connection.
    - Can this be done by copying the huge amounts of math/calculus code from the inputbox layer, into the socket layer, right under where I create the "sentnumber" variable, and modifying it delicately?
    3) The connection still has some usability and user issues - since the connection happens only once, on frame 1, it only connects if I already have a listening server when I run the client, and client can't re-connect if the server socket doesn't restart itself.
    I believe to do this, I need to make the connection happen on demand, rather than once at the start.
    For the project's requirement, I also need to allow client users to define the IP / port it's going to connect to (since the only alternative so far is editing the client in flash pro).
    In other words, I need to make a "Connect" button and two textboxes (for IP and port, respectively), which do the following:
    - On pressing "Connect", the button sets whatever is in the text boxes as the address of the IP and port the socket will connect to, then connects to that address without issues (or with a error message if it can't due to wrong IP/port).
    - The connection needs to work for non-local addresses. Not sure if it can yet.
    - On re-pressing connect, the previous socket is closed, then creates a new socket (with new IP/port, if that was altered)
    It seems like making the button should be as simple as putting the existing socket code under the function of a button, but it also seems like it's going to cause issues similar to the 'looping frames' error.
    4) Optional addition: Have a scrolling textbox like the AIR server has, to track what the connection is doing on-the-fly.
    The end result would be a client that allows user to input IP/Port, connects on button press (optionally tracking/display what the socket is doing via scrollbox), automatically alters the smiley based on what numbers are sent whilst the connection lasts, and on subsequent button presses, makes a new connection after closing off the previous one.
    Dropbox link to new client version:
    https://www.dropbox.com/s/ybaa8zi4i6d7u6a/Smiley_TCP_IP_v7.fla?dl=0
    So, starting from 1), can I, and how can I, get the number variable recognized by "inputbox" layer's code? It keeps giving me 'unrecognized variable' errors.

  • Multiple input stream in one socket connection

    Can we have multiple input streams for a java socket connection? It means that in a client/server application (creates using java socket), can we have multiple input streams for the client side program. For example, the input streams are to cater for the need of letting the user to chat and downloading some files from the chat partner at the same time. And do we need to use thread to create the multiple input streams like the case when we create a multithreaded server? Anyone out there who knows the solution please post it. Thanks in advance.

    Can we have multiple input streams for a java socket
    connection? It means that in a client/server
    application (creates using java socket), can we have
    multiple input streams for the client side program.
    For example, the input streams are to cater for the
    need of letting the user to chat and downloading some
    files from the chat partner at the same time. And do
    we need to use thread to create the multiple input
    streams like the case when we create a multithreaded
    server? Anyone out there who knows the solution please
    post it. Thanks in advance.Ok im no expert here but this is what i learned:
    a Socket can have only one InputStream (Socket.getInputStream()) and one OutputStream Socket.getOutputStream()). So you will have to create a way to make multiple Socket connections in your client program. And yes, you have to use threads for your server. if you dont the client will have to wait until the user before them is finished with the connection before being able to connect. I hope this helps you out. BTW please check out http://www.javabible.com. they have the book online now for free.
    Joeyford1

  • Establishing Socket Connection to a slow or busy server

    Currently, I'm developing an AIM-based BOT application in Java and it requires establishing a socket connection to their free and public server (host: toc.oscar.aol.com, port: 9898).
    About 75% of the time a connection will be successfully established using this:
    oConnection = new Socket("toc.oscar.aol.com", 9898);
    25% of the time when a connection fails (timeout) is due to the server being too slow or busy to respond to the connection request; however, the server will eventually response within 40 to 60 seconds.
    Let me go into details with my findings when attempting to connect to the slow/busy server:
    For experimental purposes, I used the telnet command (via the DOS command prompt: "telnet toc.oscar.aol.com 9898"), the connection will be established usually within 40 to 60 seconds.
    As I said before, the BOT application is developed in a Java environment and when attempting to establish a connection (using Java's Socket), a timeout exception gets raised when it hits the 20-seconds mark. It tells me that the Java Socket has the timeout defaulted to 20-seconds.
    I am aware that we can define the timeout settings using Socket's "setSoTimeout(x)" method; however, it's only good for AFTER a connection is established.
    Now, to sum up my findings � it clearly shows that the DOS' telnet prompt has longer "wait time" before raising any exceptions. As far as Java Socket is concerned, if a connection is not established within 20 seconds, it raises the timeout exception.
    Is there a way to stretch the "wait time" or "timeout" to be longer than 20 seconds for when a socket connection is being attempted?
    Millions of thanks in advance,
    Chad W. Taylor

    Yes, I also tried that option but no cigar. That
    timeout value is an alternative way of using
    setSoTimeout(int).
    I don't think so.
    First the Java documentation would not make sense:
    public void connect(SocketAddress endpoint, int timeout)
    throws IOException
    Connects this socket to the server with a specified timeout value. A timeout of zero is interpreted as an infinite timeout. The connection will then block until established or an error occurs.
    Parameters:
    endpoint - the SocketAddress
    timeout - the timeout value to be used in milliseconds.
    Throws:
    IOException - if an error occurs during the connection
    SocketTimeoutException - if timeout expires before connecting
    IllegalBlockingModeException - if this socket has an associated channel, and the channel is in non-blocking mode
    IllegalArgumentException - if endpoint is null or is a SocketAddress subclass not supported by this socket
    Since: 1.4
    Second my tests indicate otherwise:
    public class Main {
    public static void main(String[] args) {
    try {
         Socket conn = new Socket();
         conn.connect(new InetSocketAddress(InetAddress.getByName("toc.oscar.aol.com"),9898), Integer.parseInt(args[0]));
         System.out.println("connected under " + args[0] + " seconds");
         conn.close();
    } catch (Exception e) {
         System.out.println("not connected in " + args[0] + " seconds");
         e.printStackTrace();
    Different runs show:
    connected under 120 seconds
    and
    not connected in 20 seconds
    java.net.SocketTimeoutException: connect timed out
         at java.net.PlainSocketImpl.socketConnect(Native Method)
         at java.net.PlainSocketImpl.doConnect(Unknown Source)
         at java.net.PlainSocketImpl.connectToAddress(Unknown Source)
         at java.net.PlainSocketImpl.connect(Unknown Source)
         at java.net.Socket.connect(Unknown Source)
         at Main.main(Main.java:21)
    I speculate that the "Connection Request Timeout"
    value is platform dependent because when I use a
    different machine, the request timeout is either
    longer or shorter than 20 seconds.
    That could well be the case.
    So the proper question would be -- where is the Java
    Socket borrowing the timeout value from? The settings
    in Winsock?
    That I don't know.
    Andreas
    Chad

  • Excessive cxs socket connections created for ejb access

    We are seeing a large number of TCP connections being created to the cxs engine for ejb access in our application.
    We are running iPlanet application server 6.0, sp3 on Solaris 8. We have a web application that accesses a singleton component running in a kjs engine. That singleton accesses cmp entity beans and stateless session beans for serving client requests over the RMI/IIOP bridge. When three clients are connected and making requests, the number of TCP connections to the IIOP port (9010) starts to increase until everything freezes. I believe the "freezing" of the client apps is due to the open socket limit of 1024 being exceeded. According to the developer doc we can increase rlim_fd_max to 8192 to fix that problem.
    However, my question is why are there an increasing number of socket connections? We are caching the ejb instances in the singleton so we should not be creating a large pool of EJBs. I have verfied the large number of sockets using netstat and also using RMI runtime logging in the kjs engine.
    Does anyone have any ideas what could be happening here?
    Thanks,
    Mark

    I noticed that most of the TCP connections are made to port 32787. Can anyone from iPlanet tell me what is listening on this port? The large number of socket connections is really tying up server resources.
    Thanks,
    Mark

  • 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.

  • 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.

  • Studio Creator, Socket Connection to External Device

    I am porting an existing & successful project from Netbeans 3.6 into Studio Creator to take advantage of some of the tools in the IDE for this application. The project requires opening a socket connection from the Server PC to an external Device (PLC) that is a Client on a static IP & a dedicated fixed port.
    I am struggling to get past some security settings specific to AccessControlExceptions. Here is the code method being used to test:
    public String button1_action() {
    // Call methods to open connection, init streams, send command, and close connection.
    try {
    // Open Socket up and accept client connection
    ipSocketObject = new ServerSocket(port);
    bfSocket = ipSocketObject.accept();
    // Establish Streams
    is = new BufferedReader(new InputStreamReader(bfSocket.getInputStream()));
    os = new PrintWriter(bfSocket.getOutputStream(), true);
    System.out.println("Got to here...");
    // Clear the msCounter #13002
    os.println("r13002=0");
    pattern = "13002";
    do{ret=is.readLine();} while ((ret.indexOf(pattern)) ==-1);
    is.close();
    os.close();
    bfSocket.close();
    ipSocketObject.close();
    } catch (IOException e) {
    e.printStackTrace();
    return null;
    The Socket Connection is established, but the command string is not processed before Studio Creator generates a AccessControlException Fault. I have experiemented putting in a SocketPermission statement with out success.
    Is anyone aware of some sample code I might be able to review for opening socket connections to clients in a Studio Creator Application? Please excuse this request if too rudimentary- I am an Industrial Controls guy by trade... :)

    Sorry I know of no such application at this time, and unfortunately have not done socket work myself for many moons....
    What JDK was your previous application written under? I googled for AccessControlException and socket and seems that sometimes accounts for some issues... you can also search for that combination in the forum advanced search and might find something there.... one more long shot suggestion based upon your statement "the command string is not processed".... could it be that you need to flush the stream...?
    Sorry I don't have more to offer...
    v

  • 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

  • I can not store all my Music on my internal Macbook pro hard drive so I am storing it on a large external drive connected to my airport extrem.  How do I get Itunes to search for the music here with out trying to copy it to my laptops hard drive??

    I can not store all my Music on my internal Macbook pro hard drive so I am storing it on a large external drive connected to my airport extreme (2 TB drive plugged into the USB port).  I see the drive on my laptop and I can add and delete files no problem.  How do I get Itunes to search for the music here with out trying to copy it to my laptop's hard drive?  I don't have enough space to do that.

    How did you move the music to the external drive?  What exactly is on the drive?  The entire iTunes folder or only music?  If it is the entire iTunes folder you can do the option+start suggestion earlier.  If you copied only music and did so by dragging it there then you need to delete it again and consolidate/organize it there instead so iTunes tracks the move.  iTunes 12 for Mac: Change where your iTunes files are stored - http://support.apple.com/kb/PH19507

  • I want to use the Thunderbolt connection for an external hard drive

    I want to use the Thunderbolt connection for an external hard drive - so what port would I use on the MacBook Pro 13" for the display monitor.  Thank you!

    This is not the forum for MacBook Pro owners.
    You just need to reformat the drive in Disk Utility and erase the drive and have  Mac HFS.
    If you did need to use NTFS then you would not want -3G but Paragon NTFS for OS X x. 10.0
    Or buy something that isn't pre-formatted to Windows NT file system.
    First though make sure you have backups of your system. TimeMachine being used now?
    http://macperformanceguide.com/Mac-TimeMachine-drive.html
    http://www.apple.com/support/timemachine/
    Maybe cleanout some files you don't need.
    Install a larger notebook hard drive even.
    http://www.macsales.com/firewire has a lot of choice in Mac compatible drives and enclosures so you don't need to worry about Fantom not working at some point.
    https://discussions.apple.com/community/notebooks/macbook_pro
    https://discussions.apple.com/community/mac_os/mac_os_x_v10.6_snow_leopard

Maybe you are looking for