1
我正在使用安全连接(ssl)的java(服务器/客户端)中创建应用程序。Java ssl服务器/客户端应用程序传递字节[]
主要类有插座和流初始化:
服务器主类:
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());
我遇到的问题是,当我想通过一个byte []从服务器到客户端,字节[]已在正确的值服务器,但它到达客户端的空值。 注:当我使用的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发送字节[]()的原因,并通过该方法得到它在客户端in.read()。
但read()返回的结果在客户端和使用后保存为nbytes。我不明白的是nonceBytes的原因从服务器中的write()获得null。 –
你的建议工作EJP,但我想明白为什么read()不起作用.. 无论如何非常感谢你 最好的问候 –
它确实工作。它只是不会做你认为的事情。这不是一回事。看到Javadoc。它没有说任何它填补缓冲区。相反,它需要一定的时间来解释它可能不会。 – EJP