简体   繁体   中英

How to listen to incoming packets on a port?

I want to listen to incoming packets on port 19132 and print them out as they come, but so far my code doesn't exactly print anything at all. There is a server forwarding the packets through port 19132 to my computer, and the port is open and enabled, but still nothing is printed.

public static void listenToPort(){
    try{
        ServerSocket serverSocket = new ServerSocket(19132);
        Socket socket = serverSocket.accept();
        BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
        while(true){
            try{
                System.out.println(in.readLine());
            }
            catch(IOException e){
                System.out.println("Connection to server lost!");
                System.exit(1);
                break;
            }
        }
    }
    catch(IOException e){
        System.out.println(e.getMessage());
    }
}

On the server side there is info being sent, but the client program (this script) doesn't receive anything, what's the problem?

You are reading lines, not 'packets'. If the data being sent to this port doesn't contain newlines, readLine() will block forever, or until the peer closes the connection.

On the other hand when it does read something, or EOS, your code will spin forever printing null , because you aren't checking for readLine() returning null, at which point you must close the socket and exit the loop.

Not to mention, it might be entirely possible that the System.exit doesn't give enough time for the console to flush it's output (i'm not 100% sure if System.exit will or won't cause a flush in System.out and System.err).

Why don't you attach a debugger to your server process and see if it's even getting past the in.readLine()? As one of the other posters mentioned, if you're not sending a newline character, in.readLine() would block until you do.

Secondly, you shouldn't really use System.exit. It's bad form in most cases and leads to people wondering why the hell an app would just randomly quit. If you want to exit an app, you should allow the code to return back to the main() method, and from there you can do a System.exit if necessary.

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