gpt4 book ai didi

Java ssl 服务器/客户端应用程序传递字节 []

转载 作者:太空宇宙 更新时间:2023-11-04 07:34:19 28 4
gpt4 key购买 nike

我正在使用安全连接(ssl)的java(服务器/客户端)创建一个应用程序。

主类有套接字和流的初始化:

服务器主类:

public static void main(String[] arstring) {
DataOutputStream out = null;
DataInputStream in = null;
SSLServerSocket sslserversocket = null;
SSLSocket sslsocket = null;
...

客户端主类:

public static void main(String[] args) throws IOException {
BufferedReader console;
DataInputStream in = null;
DataOutputStream out = null;
SSLSocket sslsocket = null;
...

我在每个类中创建了各自的套接字和流:

服务器套接字和流:

SSLServerSocketFactory sslserversocketfactory = (SSLServerSocketFactory) SSLServerSocketFactory
.getDefault();
sslserversocket = (SSLServerSocket) sslserversocketfactory
.createServerSocket(port);
System.out.println("Server: listening on port: " + port + "\n");
System.out.println("Waiting for connection...." + "\n");
sslsocket = (SSLSocket) sslserversocket.accept();
connected = true;
System.out.println("Connection accepted \n");

InputStream inputstreamconsola = System.in;
InputStreamReader inputstreamreaderconsola = new InputStreamReader(
inputstreamconsola);
BufferedReader bufferedreaderconsola = new BufferedReader(
inputstreamreaderconsola);

in = new DataInputStream(sslsocket.getInputStream());
out = new DataOutputStream(sslsocket.getOutputStream());

客户端套接字和流:

 SSLSocketFactory sslsocketfactory = (SSLSocketFactory) SSLSocketFactory.getDefault();
sslsocket = (SSLSocket) sslsocketfactory.createSocket("localhost", 9999);
in = new DataInputStream(sslsocket.getInputStream());
out = new DataOutputStream(sslsocket.getOutputStream());

我遇到的问题是,当我想将字节[]从服务器传递到客户端时,字节[]在服务器中具有正确的值,但它到达客户端时为空值。注意:当我使用readUTF()和writeUTF()传递字符串时,发送的值被正确接收

“错误”发生在这种情况下:

服务器:

     byte[] nonceBytes = new byte[(int) 8];
nonce = System.currentTimeMillis();
nonceBytes = longToByteArray(nonce);

System.out.print("\nNonce gerado: ");
for (int i = 0; i < 8; i++)
System.out.print(getHexString(nonceBytes[i]));
System.out.print("\n");
out.writeUTF("pass#");
out.write(nonceBytes, (int) 0, nonceBytes.length); VALUE HERE IS CORRECT

客户:

                byte[] nonceBytes = new byte[(int) 8];
int nbytes = 0;

// read the nonce sent by server
try {
nbytes = in.read(nonceBytes); !!nonceBytes gets the null value instead of the value passed by the server!!
} catch (IOException e) {
System.err.println("Read: " + e.getMessage());
readInput = false;
break;
}

我想了解一下为什么我无法通过out.write()方法发送byte[]并通过in.read()方法在客户端获取它。

最佳答案

您忽略了 read() 返回的结果。您不能假设它填充了缓冲区。在这种情况下,您可能应该使用DataInputStream.readFully()

请注意,此问题与 SSL 无关。

关于Java ssl 服务器/客户端应用程序传递字节 [],我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17180900/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com