java - 为什么消息从未发送?

标签 java sockets client-server

出于某种原因,我从来没有从服务器返回到客户端的消息:/发生了什么?我怎样才能知道或解决这个问题?

我从客户端发送请求,服务器获取该请求,对其进行处理并生成要发送的响应。但客户从不读它。

public class Client {

private static Socket socket;

public static void main(String args[]) {
    try {
        String host = "localhost";
        int port = 13579;
        System.out.println("Conecting to : " + host + ":" + port);
        InetAddress address = InetAddress.getByName(host);
        socket = new Socket(address, port);

        //Send the message to the server
        OutputStream os = socket.getOutputStream();
        OutputStreamWriter osw = new OutputStreamWriter(os);
        BufferedWriter bw = new BufferedWriter(osw);

        String sendMessage = "103700635105281047295162150000001418    99900001000000717999000NovoTransactionsBusiness 717          VE000000000054300052810472900000000000099900001                  1803\n";

        bw.write(sendMessage);
        bw.flush();
        System.out.println("Message sent to the server : " + sendMessage);

        //Get the return message from the server
        InputStream is = socket.getInputStream();
        InputStreamReader isr = new InputStreamReader(is);
        BufferedReader br = new BufferedReader(isr);
   //But i never get the message back
        String message = br.readLine();

        System.out.println("Message received from the server : " + message);
    } catch (Exception exception) {
        exception.printStackTrace();
    } finally {
        //Closing the socket
        try {
            socket.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
 }
}

服务器运行正常!

public class Server {

private static Socket socket;

public static void main(String[] args) {
    try {
        int port = 13579;
        ServerSocket serverSocket = new ServerSocket(port);
        System.out.println("Servidor Iniciado escuchando al puerto " + port);
        while (true) {
            socket = serverSocket.accept();
            String strRequest = new BufferedReader(new InputStreamReader(socket.getInputStream())).readLine();
            System.out.println("Request Received: " + strRequest);
            String returnMessage;
            try {
                returnMessage = new NovoTrans().init(strRequest).toString();
            } catch (Exception e) {
                returnMessage = "Error: " + e.getMessage() + "\n";
            }
            BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
            bw.write(returnMessage);
            System.out.println("Sending Message: " + returnMessage);
            bw.flush();
        }
    } catch (Exception e) {
    } finally {
        try {
            socket.close();
        } catch (Exception e) {
            System.err.println(e.getMessage());
        }
    }
}
}

最佳答案

我建议您使用PrintWriter而不是 BufferedWriter。无需在每行之后调用flush,只需使用println()方法和自动刷新功能来添加新行。

Unlike the PrintStream class, if automatic flushing is enabled it will be done only when one of the println, printf, or format methods is invoked, rather than whenever a newline character happens to be output.

These methods use the platform's own notion of line separator rather than the newline character.

无需在消息本身中附加 \n

示例代码:(在服务器端和客户端类中进行更改)

// here true means auto flush when `println()` method is called
PrintWriter bw = new PrintWriter(new OutputStreamWriter(socket.getOutputStream()),true);
bw.println(returnMessage);

关于java - 为什么消息从未发送?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23935273/

相关文章:

c++ - Unix 套接字卡在 recv 上,直到我在任何地方放置/删除断点

Python:非阻塞套接字或异步 I/O

ms-access - 客户端服务器应用程序的 MS Access 后端是否存在传输速度问题?

Android:与真实设备的客户端-服务器通信

java - TreeMap java 实现 - 放入第一个元素

java - Excel转XML,编码问题

javascript - IFrame 方法 .getBody 返回 null

java - Lucene 维基百科转储

c - 在机器上查找可用的网络端口

c++ - 从 ESP8266 Arduino 连接到我的服务器