无响应的套接字读取缓冲区

Unresponsive socket read buffer

我正在尝试将数据发送到我的一台服务器并从它接收返回的 ACK。但是,在等待服务器响应时,处理会挂起。我知道确实存在连接,因为我可以看到数据到达服务器。我还知道服务器正在正确输出数据,因为我的 C# 客户端正在从服务器接收回数据。我会注意到这个客户端是 运行 在 centOS 虚拟机上。服务器是远程 windows 机器。我不认为虚拟环境会导致问题,因为我能够使用 SNMP java 客户端(SNMP4j 包)调用远程服务器。我相信我的服务器也在输出原始二进制文件,但我希望无论哪种方式都能看到某种输出。

// A Java program for a Client 
 import java.net.*; 
 import java.io.*; 

public class Client 
{ 
// initialize socket and input output streams 
private Socket socket            = null; 
private DataInputStream  input   = null; 
private DataOutputStream out     = null; 
private DataInputStream  serveroutput= null;

// constructor to put ip address and port 
public Client(String address, int port) 
{ 
    // establish a connection 
    try
    { 
        socket = new Socket(address, port); 
        System.out.println("Connected"); 

        // takes input from terminal 
        input  = new DataInputStream(System.in); 

        // sends output to the socket 
        out    = new DataOutputStream(socket.getOutputStream()); 
        serveroutput = new DataInputStream(socket.getInputStream());
    } 
    catch(UnknownHostException u) 
    { 
        System.out.println(u); 
    } 
    catch(IOException i) 
    { 
        System.out.println(i); 
    } 

    // string to read message from input 
    String line = ""; 

    // keep reading until "Over" is input 
    while (!line.equals("Over")) 
    { 
        try
        { 
            line = input.readLine(); 
            out.writeUTF(line); 
            System.out.println(serveroutput.readLine())
        } 
        catch(IOException i) 
        { 
            System.out.println(i); 
        } 
    } 

    // close the connection 
    try
    { 
        input.close(); 
        out.close(); 
        socket.close(); 
    } 
    catch(IOException i) 
    { 
        System.out.println(i); 
    } 
} 

如果您愿意分享其他代码,那就太好了。 (抱歉还不能发表评论) 尝试在 writeUTF() 上使用其他东西,可能只是 PrintStream,正如@marquis-of-lorne 所提到的 (read|write)UTF 可能会让同行感到困惑。

此外,当没有其他要发送的内容以确保数据已完整发送时,flush() 输出双方的输出可能是一个好习惯。

您也可以尝试 BufferedReader 而不是 InputDataStream,因为您正在尝试阅读行。 InputDataStream 中的 readLine() 已弃用。