I have made a client-server application which can connect over the internet. I have hard coded in my client the server's IP which is fixed.
My question is that I want a way that will not take a lot of processing and memory.
I want my client to check if internet is available and then try to connect to the server if its up and running. If not then to wait and try again.
Keeping in mind that the app is supposed to always run on your computer 24/7 and connect when possible just like skype does, in the sense that its always on and when you have the internet available and server reachable , it connects.
My client's code that connects to the server:
private void connectToServer() throws Exception {
showMessage("Attempting Connection... \n");
try{
connection = new Socket(InetAddress.getByName(serverIP), 6789);
showMessage("Ok dude you are Connected to:" + connection.getInetAddress().getHostName());}
catch(IOException e){
int x = 0;
while (true){
try {
showMessage("Sorry Your IP was not found, \nAutomatic detection:");
showMessage("Now trying again");
connection = new Socket(InetAddress.getByName(serverIP),6789);
break;
} catch (UnknownHostException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
showMessage("\nConnection not established, trying again\n");
}
/*x++;
if(x>10) break;*/
}
//throw new Exception();
}
}
This does work but takes a lot of processing and memory !
I know that by adding thread.sleep(5000), I am going to add them eventually etc...
But this doesn't solve the memory problem. My program would be running for a long time and this doesn't stop the inevitable.
Is there a better way?
THANKS
P.S : showMessage() is just my function that displays the output on my GUI
The way I checked memory was using Window's Task Manager !
(the memory increases drastically)
As you've noted in your question already, you should add a call to Thread.sleep() within the loop. As your code stands right now, it runs a tight endless loop that will be very taxing on the CPU.
As for memory usage, are you sure that the memory used is actually growing? The JVM may be allocating a large chunk of memory off the bat even for a simple program -- you should check to make sure that the usage is actually growing. If it is indeed a problem, it may just be because you're making a new Socket in each cycle of a tight loop, in which case adding the sleep() call would solve the issue by allowing the GC to take care of old Socket objects in time.
By the way, have you noticed that your code performs the exact same check again if the first one fails? Why not start the loop immediately and just perform the check once within the loop? This would allow you to significantly reduce your code's complexity. Look into the software guideline often referred to as "Don't Repeat Yourself" to learn more.
It seems you are having two problems
How to check internet is available - please refer
Preferred Java way to ping an HTTP URL for availability
Detect internet Connection using Java
How to check if internet connection is present in java?
Memory leak
You need to clean up the socket object if the connection fails.
Related
I have created a runnable jar, which runs on a single thread. The thread executes a for loop having 100 iteration. However the cpu usgae goes upto 60% on i3 processor win7 64 bit machine.
I tried to analyze the cpu usage in process Explorer
The native threads are consuming CPUs.
The native threads are all at msvcr100.dll!endthreadex+0x60
consuming cpu
I am using jdl 1.7.
Can somebody please suggest what might be going wrong here.
Here is the code:
the app accepts socket connection and processes the date sent by the client.
while (true)
{
try
{
Socket sock = ssock.accept();
// This is the function which has the for loop
obj.MyFunction();
}
catch(Exception ex)
{
ssock.close();
}
Thread.sleep(1000);
}
void MyFunction()
{
for(int i=0; i < 1000;i++)
{
// Processing done here
}
}
Profile your code, see http://docs.oracle.com/javase/7/docs/technotes/tools/index.html#jconsole for more info.
I suspect that if you try this:
ex.printStackTrace();
you might get some more information. Right now, when you get an exception, you have no idea what happened or why. You are silent about it, which is rarely the right behavior for hitting exceptions.
What is the processing? If you're trying to do a lot of work, it might not be unexpected to go to 60% cpu. What's the Big O runtime of your algo? What's the data set size?
I used the Java Knock Knock tutorial for creating a client-server connection but I cant figure out how to check if the socket is still open.
Simplified code:
try {
while ((clientMessage = inFromClient.readLine()) != null) {
//do stuff
} catch (IOException e) {
//client disconnected
e.printStackTrace();
}
}
This works great, however I noticed that when the client is Linux based the exception isn't thrown if client gets forcefully closed. I tried some suggestions posted by others but can't get any working. I tried to implement a loop that checks how long its been since last message was received but it didn't work, the loop had to be inside the loop in the above code, and the loop is only executed when a new message is received from the client. I'm very confused but I don't understand how to implement any methods of checking.
If I put the method to check for inactivity outside the above loop then it's never called because the socket loop is indefinite (unless socket is closed).
Just set a read timeout with Socket.setSoTimeout(). Set it to higher than the expected request interval, say double that. If it expires, you will get a SocketTimeoutException: close the socket.
Contrary to some of the comments, isConnected(), isBound(), isClosed(), etc. are no use for this. They tell you whether you connected, bound, closed, etc. the Socket. Not about the state of the connection.
I'm trying to communicate through sockets using TCP. The data that needs to be sent is a drawing, whilst it is being drawn. So the option would be to send all the points, or only shapes (series of points).
Since it would be nice to have it being drawn instantly, sending points seems better. It's only for local use, so a lot of data shouldn't be an issue. Now the issue I'm having is understanding how exactly the socket works. Currently my code is as follows:
while(true){
try {
Thread.sleep(10);
}
catch (InterruptedException e) {}
switch(connectionStatus){
case CONNECTED:
if(isHost){
try {
oos.writeObject(myObject);
} catch (IOException e) {
e.printStackTrace();
}
}else{
try {
myObject = (myObjectType) ois.readObject();
mainFrame.repaint();
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
break;
}
}
But needless to say, this seems rather inefficiƫnt as it's running constantly. Is there a way to only write to the ObjectOutputStream (oos) when new data is there? I guess to read you have to poll though. Does reading also clear the ObjectOutputStream?
Edit
To be clear: I want to send multiple Point-objects through a socket. So every time a Point gets added to eg the server, it should send this point to the client.
Now, what do I need to put inside the oos.writeObject()? The single Point, or a List of Points? And how are they retrieved from the ois.readObject()?
I'm a bit confused, because the writing to the ObjectOutputStream could be fast or slow. Se reading the ObjectInputStream - the way I see it - would or cause a big delay (if it reads a value every ~15ms and points get added faster than that) or cause lots of lag.
Is there a way to only write to the ObjectOutputStream (oos) when new data is there?
Yes. Whenever the user draws something, push data down the ObjectInputStream.
I guess to read you have to poll though.
That is incorrect. Typically, reading from an open stream is a blocking operation: if you attempt to read something and there's nothing there, the read method will simply block until new data is available.
For writing, you need to employ threading and synchronization technique in order to write only when data is available. One thread to notify that new data has become available, another to wait and be notified and continues execution when it is told that data has come;
Reading doesn't clear ObjectOutputStream. In fact, you can use two threads to handle input and output streams concurrently.
Reading an object is an synchronous operation, meaning your thread waits until the object is ready.
I wrote a library (which you can find on maven) that will take away some the complexity of implementing threading and synchronization yourself:
https://github.com/xtrinch/socket-live
Consists of three main components (which later result into three running threads):
SocketConnection.java: main thread, run by the user of the library, which makes sure the connection is always open
SocketRead.java: read thread which continuously attempts to read incoming messages if any
SocketWrite.java: write thread which writes any messages in write queue to socket
You also have the option to disable the read thread, if you don't need it.
Library will make sure the connection stays open at all times, reconnect upon being closed, and it's been battle tested :)
Hello I'm making a chat application in android
so overall, I have a service which contains lots of classes and threads.
in my service, i had socket input read class, socket output writer class, and pinger that in summary have 6 threads.
Actually, i'm very new with this problem, well i can say i have no idea what makes a program occupy high percentage of CPU processes. is it cause too many static variables maybe? or too many running threads maybe, or too many local variables maybe?
I don't know exactly what is going on...?
So, please share with me your experiences and knowledge
UPDATE
public void run() {
while(isRunning) {
try {
Thread.sleep(500);
if(!startCheck) {
//Log.v(TAG, "SocketQueue: "+socketTaskQueue.size()
if(socketTaskQueue.size() > 0) {
processSocketTask();// TODO
}
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
so basically, i made my threads like above example.
so, i have a vector called socketTaskQueue, and this thread job's is to check whether there's a socket task or not. if it does, then it will execute processSocketTask function that will get the top element of the vector queue and then remove it.
UPDATE
T.T this post is embarrassing! i forget to put Thread.sleep() in some of my threads!
SORRY FOR BOTHERING YOU GUYS! :p
It is caused, usually, by threads that use CPU even when they cannot accomplish useful work. For example, when a thread is waiting for something to happen, does it wait in a way that uses no CPU? Or does it keep waking up needlessly even before it can do work?
It can also be caused by threads that do work in extremely inefficient ways.
Started learning java a week ago and also decided learning the right way to work with exceptions. Java really drives me mad with the idea of specifying exceptions the method can throw as part of its signature.
I'm currently trying to implement multi-threaded server for client-server application. I was very surprised with the fact socket.close() can throw IOException. The question is, what do I do if it happens?
...
final Socket socket = .... // at this point I know that I have a good socket
try {
..... // communicating with someone on that side....
} catch(IOException e) {
// communication failed
// this fact is useful, I can log it
// and will just hang up
} finally {
try {
socket.close(); // bye-bye
} catch(IOException e) {
// anything but logging I can do here?
}
}
...
This piece of code is executed within a separate thread, so I just have to catch all the exceptions. The problem is mostly psychological - I know, I can just leave catch block empty, but I'm trying to avoid this trick.
Any thoughts?
It's quite common that you don't do anything major when closing a resource fails. Logging is probably a good idea, so that you have a chance to find out if it happens more often.
This is different if closing the resource is also the "commit" or in some other way persists the change: then you'd need to treat it just like you would treat an exception in any other part: handle it.
Note that Java 7 has introduced automatic resource management specifically to simplify these kinds of constructs. And if you learn Java now, then I'd suggest going with the latest-and-greatest.
I guess it depends if you read data from the socket or wrote data to it. If you read data and retrieved all the info you wanted then you can safely ignore the exception. But if you wrote data you probably have to assume that it did not get transmitted correctly.
Apache Commons IO (a library that I can't hardly write Java without) has a method IOUtils.closeQuietly() for just this purpose.
So you can do:
final Socket socket = .... // at this point I know that I have a good socket
try {
..... // communicating with someone on that side....
} catch(IOException e) {
// communication failed
// this fact is useful, I can log it
// and will just hang up
} finally {
IOUtils.closeQuietly(socket);
}
and save yourself 5 lines of code.
As a bonus, closeQuietly() does the right thing if the socket is null or already closed. And there are overloads for anything else Closeable as well.
As said in the comments, there's not much you can do there. I suggest you log an error anyway, this way if it ever does happen, you at least have a place to start looking.
That catches a lot of folks out, the compulsion to catch nested exceptions like that.
You should log it, ideally using something robust like Log4J, but otherwise I would say it's safe to ignore it, other than a comment saying "deliberately ignoring".
There is nothing you can do with the exception thrown by close except catch it and log it. The important thing is that if you were to let it be thrown, and if there was another exception that was thrown before the close method was reached, the close method could throw an exception that would mask the first exception, it wouldn't show up anywhere and you wouldn't know what the real problem was. So you definitely don't want that.