Keeping a socket connection alive
Hi, here is an interesting situation which I am trying to deal with. Basically what I want to have happen is the following:
Have a ServerSocket (called server) running and acception connections from users.
But where the catch comes in, is I want to be able to shut-down and restart the server without any of the connected users being disconnected.
One possible way I thought of doing this was using a middle-man style application (called client) which has a socket link betweeen it and the server, and another socket link between it and the user. But the server needs to be able to directly talk to the user and this is where I get stuck.. Basically then if the server gets shutdown, the user still has the active connect between it and the client, and when the server gets reconnected the link between the client and server is restored..
Any ideas? I don't know even if this middle-man style application is the best approach.
Thanks,
Derrick
How about having the server split in two, a lower
half that handles connections and an upper half that
handles the actual mechanism of your server's
functions. Make the lower half public, it knows
whether the upper half is alive or not, and keeps a
list of connections, buffering requests that may come
in while the upper half is being restarted.
you could do it in two processes, one for each half,
but you try to make the lower half simple and ensure
it runs forever.
the upper half could come and go as it (and you) need
it to.
now the upper half would run on a private port and
only the lower half would know about it.Yes, this is what I have done, but when the upper half wants input from the user in calles the inputsteam.. but the lowerhalf doesn't know that it has to then request the info from the user.. this is the problem I'm stuck at :(
Similar Messages
-
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 -
How to keep the internet connection alive?
Hi, I am a new Macbook user and everytime my computer goes to screen saver or sleep mode it keeps losing the internet connection. Is this normal? Is anyway to keep the internet alive even is the computer goes to "sleep mode"?
I mean, it is quite a pain to keep signing in at messenger everytime I wake up my computer or come back from screen saver
Thank youI do not know of a way. When your computer goes into sleep mode, it basically shuts itself down and stores everything in memory. Nothing is moving or working because the whole point of sleep mode is to conserve the battery. If it is really bothering you, go into System Preferences and change the amount of time it takes for the computer to go to sleep.
-
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 timeThanks 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 -
Freeware utilities for keeping network connection alive?
Hi, I am wondering if anyone has recommendations for a freeware utility that can keep the network connection alive on my 2010 mac mini.
Already have sleep, screen saver, and password lock turned off. Also using static IP.
When it sits for a while I can no longer ping it from my PC workstation or use iTunes, VNC etc from my phone.
When I open up the mac, which I am using as HTPC, it will connect right away to Google etc using Safari yet it has dropped the share connection to my PC.
Thanks! SeanThanks for the report!
-
I'm trying to write client & server application that needs to keep socket connection alive and be able to use the same socket to do multiple transactions. ( 1 transaction = Request & Response).
How can the server reliably inform the client about completion of data without closing the socket? The server doesn't know how much data is to be sent before the transaction begins.
Thank you!EJP,
I'm trying to implement something like HTTP Keep-Alive, in my case it is always turned on.
Just like a HTTP client, when it sees "Connection: keep-alive" header, it won't terminate the connection even after it has received all data for that particular transaction. I'm looking for the same solution. But I don't know how I can implement it.
One solution that i can think is, have the server send 0 bytes say for 4 times & when client receives this sequence it will know the transaction has completed, but I'm not sure if this is the optimal solution.
My situation is very similar to the way HTTP client handles HTTP Keep-Alive connection with Chunked transfer
Thanks for your response :) -
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. -
ADK - Keeping EIS Connections Alive
Hi,
I am using the ADK that comes with WL 8.1 SP3. The challenge I am facing is to keep my connections alive while there is no activity (at the TCP/IP socket level) between the app server and the EIS.
The EIS closes any sockets after 30 minutes of inactivity causing the connections to go into CLOSE_WAIT state.
Is there any method I can use within the connector to keep pinging the server and make sure these connections have TCP/IP traffic?
Has anyone used the <test-frequency-seconds> weblogic-ra.xml? What is its purpose? pinging?
Appreciate your insight..Hi
I have a requirement, which is some what similar to what is mentioned above.
I too have to ping the interface at regular intervals to keep the connection alive. I also assumed that, we can use the test-frequency-seconds attribute. But for that to work, we have to implement the interface, http://java.sun.com/j2ee/1.4/docs/api/javax/resource/spi/ValidatingManagedConnectionFactory.html, which is there only from weblogic 9.
But since our client is using weblogic 8.1, we are tied to that version.
Can anyone please assist in solving this. -
Please Help - To keep LDAP connection alive
Hi,
I have used the below function to communicate with LDAP which I have taken and modified from one of the posts in this forum.
My issue is, each time the function opens a connection, search and closing the connection and its seriously affects the performance.
I hope we can resolve this by keeping the connection alive. As I am new to this concept, I am not sure how to do this.
It would be great, if some one help me to keep the connection alive for the below function. Thanks in advance.
create or replace FUNCTION <name> (loginname VARCHAR2)
RETURN NUMBER
IS
-- Adjust as necessary.
l_ldap_host VARCHAR2(256) := '';
l_ldap_port VARCHAR2(256) := '';
l_ldap_user VARCHAR2(256) := '';
l_ldap_passwd VARCHAR2(256) := '';
l_ldap_base VARCHAR2(256) := '';
l_retval PLS_INTEGER;
l_session DBMS_LDAP.session;
l_attrs DBMS_LDAP.string_collection;
l_message DBMS_LDAP.message;
l_filter varchar2(35):='xxxx='|| loginname;
l_count NUMBER:=0;
BEGIN
-- Choose to raise exceptions.
DBMS_LDAP.USE_EXCEPTION := TRUE;
-- Connect to the LDAP server.
l_session := DBMS_LDAP.init(hostname => l_ldap_host,portnum => l_ldap_port);
l_retval := DBMS_LDAP.simple_bind_s(ld => l_session,dn => l_ldap_user,passwd => l_ldap_passwd);
-- Get attribute
l_attrs(1) := 'xxxx';
l_retval := DBMS_LDAP.search_s(ld => l_session, base => l_ldap_base, scope => DBMS_LDAP.SCOPE_SUBTREE, filter => l_filter, attrs => l_attrs, attronly => 0, res => l_message);
l_count:=DBMS_LDAP.count_entries(ld => l_session, msg => l_message);
-- Disconnect from the LDAP server
l_retval := DBMS_LDAP.unbind_s(ld => l_session);
return l_count;
EXCEPTION
WHEN OTHERS THEN
dbms_output.put_line('Error :'||SQLERRM);
return 0;
END <fun name>;
Thanks,
Praveen
Edited by: 920577 on Mar 13, 2012 9:40 AM
Edited by: 920577 on Mar 13, 2012 9:41 AMThe basic template looks as follows:
SQL> create or replace package Foo as
2
3 procedure LdapLogoff;
4 function GetData( empName varchar2 ) return number;
5
6 end;
7 /
Package created.
SQL>
SQL> create or replace package body Foo as
2
3 isLoggedOn boolean;
4
5 procedure LdapLogon is
6 begin
7 DBMS_OUTPUT.put_line( '..running logon()' );
8 isLoggedOn := true;
9 end;
10
11 procedure LdapLogoff is
12 begin
13 DBMS_OUTPUT.put_line( '..running logoff()' );
14 isLoggedOn := false;
15 end;
16
17 function GetData( empName varchar2 ) return number is
18 begin
19 if not isLoggedOn then
20 LdapLogon();
21 end if;
22
23 DBMS_OUTPUT.put_line( '..running GetData() for '||empName );
24 return(
25 round(DBMS_RANDOM.Value(1,100))
26 );
27 end;
28
29
30 --// main()
31 begin
32 DBMS_OUTPUT.put_line( 'Package Foo loaded into memory' );
33 isLoggedOn := false;
34 end;
35 /
Package body created.
SQL>
SQL>
SQL> select empno, ename, Foo.GetData(ename) as ID from emp order by empno;
EMPNO ENAME ID
7369 SMITH 23
7499 ALLEN 47
7521 WARD 88
7566 JONES 71
7654 MARTIN 91
7698 BLAKE 28
7782 CLARK 92
7788 SCOTT 91
7839 KING 48
7844 TURNER 89
7876 ADAMS 64
7900 JAMES 16
7902 FORD 18
7934 MILLER 35
14 rows selected.
Package Foo loaded into memory
..running logon()
..running GetData() for SMITH
..running GetData() for ALLEN
..running GetData() for WARD
..running GetData() for JONES
..running GetData() for MARTIN
..running GetData() for BLAKE
..running GetData() for CLARK
..running GetData() for SCOTT
..running GetData() for KING
..running GetData() for TURNER
..running GetData() for ADAMS
..running GetData() for JAMES
..running GetData() for FORD
..running GetData() for MILLER
SQL>
SQL> select empno, ename, Foo.GetData(ename) as ID from emp where rownum = 1;
EMPNO ENAME ID
7369 SMITH 9
..running GetData() for SMITH
SQL>
// call Foo.Logoff manually when done, or leave it to
// Oracle to close and release resources when the
// session terminates -
Keep a Socket Server connection/port open for incoming requests
Hi,
I have a socket server which listens to the incoming messages. The problem is that the socket server terminates the socket connection once it receives a message.
I want this Socket server to keep on running and process all the requests it receives.
Can you please advise which stream shall be kept open for this to be achieved? Below is the code for your reference.
Thanks!
import java.net.*;
import java.io.*;
public class SocketServer
public static void main(String[] args) throws IOException
ServerSocket serverSocket = null;
String result = null;
SocketServer sockServer = new SocketServer();
try
serverSocket = new ServerSocket(4444);
catch (IOException e)
System.exit(1);
Socket clientSocket = null;
try
clientSocket = serverSocket.accept();
clientSocket.setSoTimeout(30000);
catch (IOException e)
System.exit(1);
PrintWriter out = new PrintWriter(clientSocket.getOutputStream(), true);
BufferedReader in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
String inputLine;
inputLine = in.readLine();
if((inputLine == null) || (inputLine.length() < 1))
throw new IOException("could not read from request stream");
else
result = sockServer.parseString(inputLine);
out.println("|0|OK|");
InputStream is = null;
FileOutputStream fout=null;
BufferedInputStream bufIn = null;
HttpURLConnection con = null;
ByteArrayOutputStream baos = null;
try
URL url = new URL("http","10.176.96.64",8080,result);
con = (HttpURLConnection)url.openConnection();
is = con.getInputStream();
bufIn = new BufferedInputStream(is);
fout=new FileOutputStream("Z:\\Clips\\Cache\\"+result);
baos = new ByteArrayOutputStream();
int c = bufIn.read();
while(c != -1)
baos.write(c);
c = bufIn.read();
baos.writeTo(fout);
catch(MalformedURLException mue)
System.err.println ("*********In Download File: Invalid URL");
catch (IOException ioe)
System.err.println ("*********In Download File: I/O Error - " + ioe);
finally
try
baos.close();
bufIn.close();
fout.close();
is.close();
con.disconnect();
catch(Exception ex)
System.out.println("*********In Download File: Exception Occured: "+ex.toString());
out.close();
in.close();
clientSocket.close();
serverSocket.close();
}In a truly unexpected turn of events.. this question has been crossposted.
http://forum.java.sun.com/thread.jspa?threadID=5127579
Good job singalg. I highly recommend that instead of accepting that there is anything wrong with your understanding of how this should work and reviewing the tutorials you should instead repost this question daily, Each day choosing a different forum. -
How to keep connection alive?
I wondering if there is any way to keep connection alive during some period of inactivity.
I have the SQL Developer 1.2.1 (it is not easy to update as I have no admin privileges on work computer) under Windows XP, connecting to Oracle9i Enterprise Edition Release 9.2.0.6.0.
The inconvenience is that the connection become dropped after some inactivity time.
What I have to do is to disconnect and connect again. But if I run any query in dropped connection condition it would take long time before it come back with a message that there is no connection.
I could not find any kind of 'stay connected' option. (Like it is in some other application with time set possibility to send a some request to a server just to stay connected (for exm: PuTTY))
To do it by myself it would be done by having some continuously looping script, that would run some simple select (say, sysdate) periodically, but I do not know if it possible to do it from SQL Developer.
If it done in PL-SQL, it will be processed in Oracle, not in SQL Developer; so, it is not useful.
Does anybody have or know any suggestion or advice to keep connection stay active?
Appreciate any help!
Alex
Message was edited by:
alex5161The trouble is shared connections. While the dbms_lock.sleep is sleeping, the connection will be frozen.
Having said that, the real solution is to fix how sqldeveloper handles lost connections. Session timeouts are usually there for a reason and client software needs to learn to live with it. -
Hi. I've noticed that after moving from opensuse to arch, my wifi connection dies on me after inactivity. I've tried this workaround:
* Add a crontab to ping a website every 15 minutes. I'm using this command:
* ping -c 4 www.google.com
However, the connection still dies. Is there a better way to keep my connection alive? Perhaps if I increase the number of packets?As per this ubuntu forum post, I found something that might do the trick
http://ubuntuforums.org/showthread.php?t=420959
Adapted to arch, this may work:
#!/bin/sh
HOST=www.google.com
ping -c 1 -W 10 $HOST &>/dev/null
if [ $? -eq 0 ]; then
#ping is ok
exit
else
#first try
ifconfig wlan0 down
sleep 3
ifconfig wlan0 up
sleep 10
ping -c 1 -W 10 $HOST &>/dev/null
if [ $? -eq 0 ]; then
exit
else
#second try
/etc/rc.d/wlan restart
/etc/rc.d/network restart
iwconfig wlan0 essid NOAH_S_ARK
sleep 10
ping -c 1 -W 10 $HOST &>/dev/null
fi
fi
The corresponding root crontab entry to run it every 20 minutes is
*/20 * * * * <nameofscript>
Gonna try when I get home. -
OSB using socket Transport ,how to keep a TCP connection open
hi my firends,
i met a problem , our project need build an OSB to control a socket service which is able to transfer a big data file (maybe a voice file,*.wav),and the client program will play the voice file on live.
So my solution is that : keep a socket (tcp) connection open,client listen port and makes date play.
but i can't make the OSB socket transport alway open,it will timeout after a few second if have none date received.
how could i deal with it ... pls let me konw if you have any idea...i will wait you on line
thanks guysHi,
I'm not sure if that's achievable using OSB, and even if it was, I don't think OSB was designed having this type of application in mind...
I understand that you need a media streaming solution and I'm pretty sure that there are plenty of tools out there that can help you in doing that, and maybe some of them can be integrated with OSB in some way...
Cheers,
Vlad -
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.
Maybe you are looking for
-
Windows Vista Ultimate (RED)
I bought this today with my school discount. Im toally impressed for $64.95. By the way. The Vista Basic SP1 DVD Worked with the product key that I had. Ive learned that all versions of Vista are on one DVD. Its the product key that determines the fe
-
Hey everyone, Wondering if any of you can help clarify something for me. I've switched off notifications through Notification Centre for all apps, but I've been told that this doesn't fully switch notifications off. Is that correct? I assumed that wh
-
2 variables for same characteristic in planning level in BPS
Hello, I would appreciate your help implementing this scenario: a user has access to certain versions and should be a able to copy data between 2 of those versions. We have 4 versions on our master data: 001, 002, 003 and 004. A certain user should b
-
Not sure. Possibly since I got a new laptop with Win 7 or maybe since my last Firefox update. I usually have a very current version of Firefox and Thunderbird. My laptop is 64 bit.
-
How. To change my payment details
How to change payment details