从Android设备发送散列字节数组到服务器套接字并存储它

时间:2014-03-05 14:31:20

标签: java android sockets hash bytearray

我在接收端遇到问题,即服务器。它正在接收数据,我试图将这些数据存储在一个字节数组中。我在while循环中执行此操作,但它永远不会终止,我无法弄清楚原因。

Android代码段:

try {
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        MessageDigest digest = MessageDigest.getInstance("SHA-256");

        byte[] keyBytes = keystore.get("secretkey");
        byte[] nonceBytes = nonce.getBytes("UTF-8");

        outputStream.write( nonceBytes );
        outputStream.write( keyBytes );

        byte[] bytesToEncrypt = outputStream.toByteArray();

        byte[] hashedBytes = digest.digest(bytesToEncrypt);

        Socket clientSocket = new Socket(myserver, myport);
        OutputStream outToServer = clientSocket.getOutputStream();
        outToServer.write(hashedBytes);
    }

服务器代码段:

try {
    ServerSocket serverSocket = new ServerSocket(8311);

    while(true) {
        Socket connectionSocket = serverSocket.accept();
        System.out.println("Receivied something..");

        InputStream inFromClient = connectionSocket.getInputStream();

        byte[] buffer = new byte[connectionSocket.getReceiveBufferSize()];

        try {
            System.out.println("Trying to store data in byte array");
        int bytesRead = -1;

        while( ( bytesRead = inFromClient.read( buffer ) ) != -1 ) {  
            baos.write( buffer, 0, bytesRead );
        }

        // This never prints
        System.out.println("Done");


        challengeReceived = baos.toByteArray();
        } 
        catch(Exception e) {
            e.printStackTrace();
        }
}

此实现永远不会打印“完成”。任何建议表示赞赏。

1 个答案:

答案 0 :(得分:0)

服务器退出

    while( ( bytesRead = inFromClient.read( buffer ) ) != -1 ) {  
        baos.write( buffer, 0, bytesRead );
    }
客户端关闭连接时

循环。

尝试使用close()调用关闭客户端的连接。这样:

outToServer.write(hashedBytes);
clientSocket.close();