i have a jar file: myServerSide.jar,
this jar takes request from client apps, processes them, each one ina thread and renders a response
i've put my jar on linux, but i want it to be ALWAYS running
if i do java -jar myServerSide.jar & for no reason it stops after a while
i also tried deamon -- java -jar myServerSide.jar & it also stops
do you know the reason why?
what should i do,so that it stays always running, and never exit.(is it necessary to make it a service)
thanks for your help
(i'm hosting my jar on linode (a VPS) if it is related)
this is the code for my server
try
{
FTLogger.getInstance().logMessage(Level.FINE, "S: Connecting...");
ServerSocket serverSocket = new ServerSocket(SERVERPORT);
while (true)
{
Socket client = serverSocket.accept();
Thread serverThread = new Thread(new ServerThread(client));
serverThread.start();
}
}
catch (Exception e)
{
FTLogger.getInstance().logMessage(Level.SEVERE, "S: Error getting connection", e);
}
in my logs, i don't see any error, and when working the jar works as it should.
(if you're sure that it's smthg from my code, should i open another question, and discard this?)
if i do java -jar myServerSide.jar & for no reason it stops after a while
The reason it stops could be (probably is) in your code.
Debugging it should tell you why it stops.
Assuming you don't have access to screen you can try nohup java -jar myServerSide.jar > log.out &
If an java.lang.Error occurs it wouldn't be catched by
catch (Exception e) {
...
}
only
catch( Throwable t ) {
...
}
would do it.
I think that you should ensure this programatically by something like infinite loop waiting for requests from client and delegating them to separate threads for processing:
// this is very high-level and obviously a exit point from this loop should be provided
while (true) {
Request r = waitForRequest();
processRequestInNewThread(r);
}
Or is there something more you need that I'm missing? Maybe a sample code from your implementation of request handling will help.
You should give us some code. The first thing that pops into my mind is that you need to make sure your method that accepts the connections from clients need to run in an infinite loop. For example:
while (true) {
acceptAndParseRequest();
}
If you launch a java application, and you embed your code into a loop:
while(true){
...
}
It will never stop, the only reason why it should stop it's because an exception is launched (do you consume resources inside the while) ?
In case it really stops, try to understand what is the problem in this way:
while(true){
try{
... your code ....
}catch(Throwable t){
system.out.println("This is my problem:" + t.printStackTrace);
}
}
Sure it helps
Related
I ran in to a problem using a Jetty Websocket when connecting to an endpoint and sending Strings to it.
First off, the websocket is used to connect to a Sonos speaker using a Jetty websocket. Jetty version is 9.4.48 .
These connections can of course be interrupted by a loss of power, connection issues, ...
The problem occurs when trying to clean up the threads when a the connection is interrupted. The HTTPclient is able to end all it's threads succesfully, except for 1 thread. This is a thread that is created when the Jetty
session.getRemote().sendString(message);
is called.
I think the problem lies with the fact that I keep sending websocket strings but they never get answered. I found this thread-leak with JProfiler.
Things I've tried already:
Using a SendStringByFuture or SendString with a new WriteCallback:
session.getRemote().sendString(message, new WriteCallback() {
#Override
public void writeFailed(Throwable throwable) {
log.info(LOG_TAG + " -- Write Failed!");
log.info(throwable.getMessage());
log.info(throwable.getCause().getMessage());
try {
session.getRemote().flush();
} catch (IOException e) {
throw new RuntimeException(e);
}
}
#Override
public void writeSuccess() {
log.info(LOG_TAG + " -- Write Success!");
}
});
Any ideas what is causing this thread to stick around?
I've had test cases that caused OutOfMemroyExceptions because of this thread leak.
Thanks in advance
I expected the thread to get removed by the garbage collector since it isn't used anymore, but instead the threads stay alive and can cause outofmemoryexceptions when JVM is unable to start a new thread.
I wonder how to handle exceptions correctly within a client server application. My client sends an information to the server(thread) which receives it within its run method.
I have already read something about uncaught exception handling when dealing with exceptions in the run method but want to know if this is the correct way to do it in my case.
I want to catch the exception on the client side.
I have in mind to do the following:
//Server
run(){
try{
...
}
catch(Exception e){
clientoutputstream.write(...); //transmitting the error
}
}
Any other suggestions?
You should put a try { } catch (IOException) around your read() call so you know if the other end has closed the connection. The other thing you might want to do is to put a try { } catch(Throwable) { } around the processing code so you can manually close the socket (Be very careful about catching Throwable) But if you just let the thread die the Socket will be closed when the object is garbage collected or when it times out
I'm programming in Java to talk with a device connected to a com-port (connected to the PC through USB, but by an RS232 to USB cable in between). I've written a program that talks with jssc and that functioned correctly under Windows, it kept working for a longer time even when nothing happens, like it should. Under Linux the program stops responding after a minute of 2 or 3 and I wonder why.
The run statement is as follows
public void run() {
while (stayConnected) {
try {
serialPort.writeBytes(pollBuf);
readResponse(false);
Thread.sleep(400);
serialPort.writeBytes(readEvents);
readResponse(true);
} catch (InterruptedException ie) {
logger.error("Interrupted exception: " + ie.getMessage());
} catch (SerialPortException spe) {
logger.error("SerialPortException: " + spe.getMessage());
}
}
}
To know where the program hangs I've added loglines and I found out that the last command to function correctly is the last call to readResponse(true) and the first to stop returning is serialPort.writeBytes(pollBuf).
Hoping that it would solve the issue I split the 400 ms sleep in two and placed the other sleep before serialPort.writeBytes(pollBuf). That doesn't help. Somehow the serialPort.writeBytes function just never returns and doesn't throw an exception either.
Does anyone have a guess of what the failure might be? It's not the stayConnected boolean as I never call the function yet that sets it so false;
edit: I've just added a counter and the program gets into the loop 283 and 285 times when I run it twice, that's pretty close and both around 2 minutes ...
I'm having a very similar problem under Windows 7. I've deployed my software to a clients PC and after about 5 to 6 hours the serial port can be opened but not able to be written to.
As per the example my code is similar:
String readPort(String command, int byteToRead) {
String Input = null;
if (opened == true) {
try {
serialPort.writeString(command);
Input = serialPort.readString(byteToRead);
} catch (SerialPortException ex) {
System.out.println(ex);
}
}
return Input;
}
The line of code that does not return is
serialPort.writeString(command);
I had exactly the same issue, the cause was another thread closing the port while the main one still reading, i see your code snippet is about a Runnable so carefully check you multithread management.
I want to create simple download accelerator.
How it works
Server wait for incoming connection.
Client connect to server.
Then, server send file size to client and wait for download connection.
Client got file size, then create download thread and these thread are connect to server.
After server got connection from each thread, server will wait for start and end offset file from thread.
Each thread send start and end offset file to server.
After server got offsets, server will send the portion of file to thread.
Each thread will read and write to file. For example, buffer.p01, buffer.p02, buffer.p03
Client merge all file into one file order by sequence. ( Not yet implemented )
I think server side it works correctly but client side it has some problem.
The problem is if I set MAXTHREAD to 1, it works correctly. But if I set more than one, it stuck somewhere forever.
This is server side code..
http://pastebin.com/TEakGB0c
and this is client side code with multithreading
http://pastebin.com/wKhP7DxS
Thanks your.
You have a pretty big obvious problem. ServerSocket's accept method returns a new socket every time. In your server code here
initSocket = servSock.accept();
initSocket is a class member field which means you will over write the old socket and never close it. You should start a new thread to handle this socket and from what I see it looks like you just keep reusing the same socket. That won't work. Look at tutorials on how to open sockets. Sorry I can't help more but there is a lot of things going on here that just won't work. Maybe you can start focusing on part of the code and we can help more.
I agree, it could be a small issue or it could be a big one, some example code would help us aid you, If you try to connect to a server 3 times using the same port you will get an error because you can only have 1 connection per port, the problem could be super simple or very complex, if you edit your post and add your code then we can better help you.
Please close your OutputStream os
Sending u a snippet
public static boolean sendFile() {
int start = Integer.parseInt(startAndEnd[0]) - 1;
int end = Integer.parseInt(startAndEnd[1]) - 1;
int size = (end - start) + 1;
try {
os = initSocket.getOutputStream();
os.write(byteArr, start, size);
os.flush();
System.out.println("Send file to : " + initSocket);
} catch (IOException e) {
System.out.println(e.getLocalizedMessage());
disconnected();
return false;
} finally {
if (os != null) {
try {
os.close();
} catch (IOException ex) {
Logger.getLogger(FileServer.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
return true;
}
i have a java project, works as a server. when an instance of this project running, i can run another instance.
how can i avoid running of more than one instance on same java project at the same time?
(Stop the server when another instance is detected)
import java.net.ServerSocket;
.....
private static final int PORT = 9999;
private static ServerSocket socket;
public static void main(String[] args) {
try {
socket = new ServerSocket(PORT, 0, InetAddress.getByAddress(new byte[] { 127, 0, 0, 1 }));
{/*here write your own code taht must be run in the main*/}
} catch (BindException e) {
System.err.println("**********************************Already running.");
System.exit(1);
} catch (IOException e) {
System.err.println("************************************Unexpected error.");
e.printStackTrace();
System.exit(2);
} catch (Exception e) {
System.err.println("************************************ Error");
System.exit(3);
}
}
i used this code and it work try it
Easiest way is to use lock file, this causes problems if the app crashed. Try writing the pid into the lock file, you can check if that pid exists (although not natively maybe in a wrapper shell script).
If you are running server can you not check if a port is open, or better still maybe a jmx instance on a known port.
I totally support #vickirk - his approach allows the second "un-needed" instance of your server become "dormant" instead of simply terminating, i.e. periodically run to perform a check if the "active" instance is still actually active/present, and take over if it went down.
In the distrubuted case, if the requirement is to have a single server instance spanning multiple machines, the approach is still to find a common resource that can be locked, physically or logically. For that purpose, I personally use a control database table where an active process writes its PID and "heartbeat", and all others are checking for that "heartbeat" to be fairly recent, and become active if its not.
you can write simple command line script for app start - that check is server runs before actually run new instance. Just check url with wget for example...