简体   繁体   中英

Java program terminates after registering Listeners

Hello people on the internet!

I have a problem with my code in java, I'm shure it's just a beginner error, but I can't quite get WHAT the problem is.

import java.io.IOException;
import java.io.PrintStream;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.Random;

public class MultiThreadChatClient
{
private static Socket clientSocket = null;
private static PrintStream os = null;
private static boolean closed = false;

private static void start() 
{           
    int portNumber = 2222;
    String host = "localhost";

    System.out.println("Host=" + host + ", port=" + portNumber);

    try
    {
        clientSocket = new Socket(host, portNumber);
        os = new PrintStream(clientSocket.getOutputStream());
        os.println("KeyListener ID: " + new Random().nextInt());
    } 
    catch (UnknownHostException e) 
    {
        System.err.println("Finner ikke hosten " + host);
    }
    catch (IOException e) 
    {
        System.err.println("Error, fant ingen åpen server på " + host);
    }

    if ( clientSocket == null || os == null )
    {
        closed = true;
    }
    Listener.startListener();
}

public void stop()
{
    closed = true;
    os.close();
    try
    {
        clientSocket.close();
    }
    catch (IOException e) 
    {
        e.printStackTrace();
    }
}

public static void send(String msg)
{
    if (!closed)
    {
        os.println(msg);
    }
}

public static void main( String[] args )
{
    start();
}
}

And the class:

import org.jnativehook.GlobalScreen;
import org.jnativehook.NativeHookException;
import org.jnativehook.keyboard.NativeKeyEvent;
import org.jnativehook.keyboard.NativeKeyListener;
import org.jnativehook.mouse.NativeMouseEvent;
import org.jnativehook.mouse.NativeMouseInputListener;
import org.jnativehook.mouse.NativeMouseWheelEvent;
import org.jnativehook.mouse.NativeMouseWheelListener;

public class Listener implements NativeKeyListener, NativeMouseInputListener, NativeMouseWheelListener
{
public void nativeKeyPressed(NativeKeyEvent e) 
{   
    MultiThreadChatClient.send(NativeKeyEvent.getKeyText(e.getKeyCode()));
}

public void nativeKeyReleased(NativeKeyEvent e) 
{
}

public void nativeKeyTyped(NativeKeyEvent e)
{
}

public void nativeMouseClicked(NativeMouseEvent e) 
{
}

public void nativeMousePressed(NativeMouseEvent e) 
{
}

public void nativeMouseReleased(NativeMouseEvent e) 
{
}

public void nativeMouseMoved(NativeMouseEvent e)
{
}

public void nativeMouseDragged(NativeMouseEvent e) 
{
}

public void nativeMouseWheelMoved(NativeMouseWheelEvent e)
{
}

public static void startListener()
{
    try 
    {
        GlobalScreen.registerNativeHook();
    }
    catch (NativeHookException ex)
    {
        System.err.println("Et problem oppsto.");
        System.err.println(ex.getMessage());

        System.exit(1);
    }
    Listener listener = new Listener();
    GlobalScreen.getInstance().addNativeKeyListener( listener );
    GlobalScreen.getInstance().addNativeMouseListener( listener );
    GlobalScreen.getInstance().addNativeMouseMotionListener( listener );
    GlobalScreen.getInstance().addNativeMouseWheelListener( listener );
}
}

My problem is that right after registering the key listeners in the Listener class the program terminates with the code '0'.

It used to work until I did something and now it just terminates upon start. I tried to start a thread just to keep the program alive, and that worked, but noone of the listeners worked.

Thank you in advance!

Update:

I tried with the exampleclass from https://code.google.com/p/jnativehook/wiki/examples but event that does not work anymore?!

the same problem as with the above problem. Both my classes ( the ones above ) and the example calsses used to work, but now they all just terminates after registering the listeners ( The main method in the example classes )

Is it my eclipse or anything that is wrong here?

如果不运行您的代码,我的猜测是jvm的“ main”线程启动了侦听器,但随后没有阻塞,因此退出了“ main”方法。

Your program runs and ends. It is over, finished and is done. So it "stops".

Starting a (new) thread would be the right way. But do not use a thread to "keep the program alive", use it for something useful. In your case, a thread could open a socket and listen on that socket for incoming messages (you are writing a chat client, right?). If a message comes in, the thread will handle it and response.

Or make a new thread out of your listener - instead of a method startListener , you could create a method called startListenerThread .

Your progamm flow would be:

  • start main method (the main thread)
  • the main thread starts the socket thread
  • the main thread starts the .... (what ever)
  • the main thread waits until all other threads have finished (it blocks)

Starting with Windows Vista, Microsoft made un/under-documented changes to the way SetWindowsHookEx() works. Basically they have set a upper limit on the number of hooks that can be used and they have also set processing time limits on each callback. There is no way to fix, detect or otherwise work around this new behavior. Please let me know how you managed to keep that many copes of the hook running and what version of the library you are using. Additional information on the problem can be found here .

Update: I wanted to answer the original question about the inconsistencies in the way the application terminates after reaching the end of main. There were some issues in the way the native thread was attaching to the JVM prior to 1.2.0 RC1 that were causing part of the issue you were describing above. That native thread should now be attached as a user thread, opposed to a daemon thread, which will prevent the application from terminating as long as the native thread is registered. I believe this was the behavior you were originally expecting from the library.

I rebooted my computer and it worked again. My program does not properly shut down and gets stuck in memory as a Listener. It seems that the program only works until there are about 8 other of the same application in memory running. I do not understand how this happen, but after I fix my shutdown precedure everything should be fine again.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM