首页 > 解决方案 > Java Eclipse - 从命令提示符运行时的输出与通过 IDE 运行时的输出不同

问题描述

这是在超级用户https://superuser.com/questions/1364594/java-eclipse-output-when-running-from-command-prompt-is-not-the-same-as-throug上问的,但有人告诉我问而是在这里。

我对 Java 和 Eclipse IDE 非常陌生,在 Windows 上从命令提示符运行我的 Java 代码时遇到问题。如果我通过 Eclipse IDE 运行代码,这就是我得到的输出

Message number 0
Message number 1
Message number 2
Timeout. Client is closing.

但是,如果我通过命令提示符运行代码java test.Main,我会在命令提示符的消息之间得到很多空行。

//Hundreds of empty lines 
Message number 0
//Hundreds of empty lines
Message number 1
//Hundreds of empty lines
Message number 2
//Hundreds of empty lines
Timeout. Client is closing.

如果字符串为 NULL 或为空,我尝试添加简单的检查以不打印任何输出,但它没有工作。下面是我的代码。我在这上面花了很多时间,但不知道是什么原因造成的。

主.java

package test;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

// create 5 processes

public class Main {

    public static void main(String[] args) {
        int port = 50001;
        UdpUnicastServer server = new UdpUnicastServer(port);
        UdpUnicastClient client = new UdpUnicastClient(port);

        ExecutorService executorService = Executors.newFixedThreadPool(2);
        executorService.submit(client);
        executorService.submit(server);
    }
}

udpUnicastClient.java

package test;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.SocketException;

/**
 * Created by dan.geabunea on 6/3/2016.
 */
public class UdpUnicastClient implements Runnable {
    private final int port;

    public UdpUnicastClient(int port) {
        this.port = port;
    }

    @Override
    public void run() {
        /**
         * Bind the client socket to the port on which you expect to
         * read incoming messages
         */
        try (DatagramSocket clientSocket = new DatagramSocket(port)) {
            /**
             * Create a byte array buffer to store incoming data. If the message length
             * exceeds the length of your buffer, then the message will be truncated. To avoid this,
             * you can simply instantiate the buffer with the maximum UDP packet size, which
             * is 65506
             */

            byte[] buffer = new byte[65507];

            // Set a timeout of 3000 ms for the client.
            clientSocket.setSoTimeout(3000);
            while (true) {
                DatagramPacket datagramPacket = new DatagramPacket(buffer, 0, buffer.length);

                /**
                 * The receive method will wait for 3000 ms for data.
                 * After that, the client will throw a timeout exception.
                 */
                clientSocket.receive(datagramPacket);

                String receivedMessage = new String(datagramPacket.getData());
                if(receivedMessage != null && !receivedMessage.isEmpty()) {
                    System.out.println(receivedMessage);
                }
            }
        } catch (SocketException e) {
            e.printStackTrace();
        } catch (IOException e) {
            System.out.println("Timeout. Client is closing.");
        }
    }
}

UdpUnicastServer.java

package test;

import java.io.IOException;
import java.net.*;

/**
 * Created by dan.geabunea on 6/3/2016.
 */
public class UdpUnicastServer implements Runnable {
    /**
     * The port where the client is listening.
     */
    private final int clientPort;

    public UdpUnicastServer(int clientPort) {
        this.clientPort = clientPort;
    }

    @Override
    public void run() {
        /**
         * Create a new server socket and bind it to a free port. I have chosen
         * one in the 49152 - 65535 range, which are allocated for internal applications
         */
        try (DatagramSocket serverSocket = new DatagramSocket(50000)) {
            // The server will generate 3 messages and send them to the client
            for (int i = 0; i < 3; i++) {
                String message = "Message number " + i;
                DatagramPacket datagramPacket = new DatagramPacket(
                        message.getBytes(),
                        message.length(),
                        InetAddress.getLocalHost(),
                        clientPort
                );
                serverSocket.send(datagramPacket);
            }
        } catch (SocketException e) {
            e.printStackTrace();
        } catch (UnknownHostException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

标签: javaeclipse

解决方案


I suspect a Charset (encoding) problem.

Try passing a Charset name to both String.getBytes() in the server app, and the String constructor in the client app, e.g.

   byte[] bytes = message.getBytes("UTF-8");
    DatagramPacket datagramPacket = new DatagramPacket(
                            bytes,
                            bytes.length,
                            InetAddress.getLocalHost(),
                            clientPort
                    );

and

String receivedMessage = new String(datagramPacket.getData(), "UTF-8");
  • Edit - also make sure that you're using the correct length for the outbound datagram, recognizing that the length of the string in chars is not necessarily the length of the byte array (in bytes). Updated the example code.

推荐阅读