Java套接字 - 服务器响应始终为null

时间:2016-05-31 15:21:06

标签: java sockets tcp

我必须连接服务器(我无法访问服务器代码),但传输协议(Socket)是:

  

(客户) - >数据

     

ack< - (服务器)
   数据响应< - (服务器)

     

(客户) - > ACK

假设服务器应该总是快速响应。我连接到服务器,我发送数据,但响应是NULL,如果我调试我的代码,当我捕获响应时发生异常: “java.net.SocketException:软件导致连接中止:recv失败”

我的代码:

public static void main(String[] args){
    try{
        String order = "datahere";
        String responseServer;   
        BufferedReader inFromUser = new BufferedReader( new InputStreamReader(System.in));  

        Socket clientSocket = new Socket();
        InetSocketAddress sa = new InetSocketAddress("XXX.XX.XX.XX", 9300);
        clientSocket.connect(sa,500);

        DataOutputStream outToServer = new DataOutputStream(clientSocket.getOutputStream());   
        BufferedReader inFromServer = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));    
        outToServer.writeBytes(order);   
        responseServer = inFromServer.readLine();//exception if I try to debug my code   
        System.out.println("From server: " + responseServer); //responseServer is NULL
        clientSocket.close(); 

    } catch (IOException ex) {
            System.out.println("Error: "+ex);
    }

}

那是错的?有什么想法吗?

我尝试禁用防火墙并为端口9300添加规则,但结果是一样的。

客户端在Vb.Net中给了我一个示例代码,它应该可以工作,我尝试用Java复制它。

Vb.Net中的代码:

Dim message As String = "datahere";

 Try
     Dim data As [Byte]() = System.Text.Encoding.ASCII.GetBytes(message)

     Dim client As New TcpClient(ip, port)
     Dim stream As NetworkStream = client.GetStream()
     stream.Write(data, 0, data.Length)

     data = New [Byte](2048) {}

     Dim responseData As [String] = [String].Empty
     Dim bytes As Integer = stream.Read(data, 0, data.Length)
     responseData = System.Text.Encoding.ASCII.GetString(data, 0, bytes)

     stream.Close()
     client.Close()

 Catch ex As Exception

End Try

SOLUTION:

Socket clientSocket = new Socket();
InetSocketAddress sa = new InetSocketAddress("XXX.XX.XX.XX", 9300);
clientSocket.connect(sa,500);

clientSocket.getOutputStream().write(order.getBytes("ASCII"));

byte[] data = new byte[2048];
int bytes = clientSocket.getInputStream().read(data, 0, data.length);
String responseData = new String(data, 0, bytes, "ASCII");
System.out.println("From server: " + responseData);

//Another way to catch the response:
//InputStreamReader in = new InputStreamReader(clientSocket.getInputStream());
//int data1 = in.read();
//while(data1 != -1) {
//   System.out.print((char) data1);
//   data1 = in.read();
//}

clientSocket.close();

2 个答案:

答案 0 :(得分:1)

以下是VB code

java的翻译
public static void main(String[] args) throws IOException {
    String order = "datahere";

    // Try-with-resource statement will close your socket automatically
    try (Socket clientSocket = new Socket("XXX.XX.XX.XX", 9300)) {
        // Send to the sever the order encoded in ASCII
        clientSocket.getOutputStream().write(order.getBytes("ASCII"));
        // Sleep until we have bytes to read available
        while (clientSocket.getInputStream().available() == 0) {
            Thread.sleep(100L);
        }
        // Create the buffer of exactly the amount of bytes available without blocking
        byte[] data = new byte[clientSocket.getInputStream().available()];
        // Read the bytes from the server and put it into the buffer
        int bytes = clientSocket.getInputStream().read(data, 0, data.length);
        // Decode what has been read from the server that was encoded in ASCII
        String responseData = new String(data, 0, bytes, "ASCII");
        System.out.println("From server: " + responseData);
    }
}

答案 1 :(得分:0)

DataInputStream dis = new DataInputStream( new InputStreamReader(clientSocket.getInputStream()));

    while(dis.available()>0){
    //reads characters encoded with modified UTF-8
    String temp = dis.readUTF();
    System.out.print(temp+" ");
        }

尝试使用dataInputStream代替bufferedReader并使用readUTF()中的dataInputStream方法来读取UTF字符。