我正在使用安全连接(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()方法在客户端获取。