我正在编写一个客户端/服务器应用程序,其中客户端向服务器发送用户名,服务器响应挑战,但我遇到了接收质询的客户端问题。似乎挑战只是被删除或替换为另一个字节数组(每次都恰好相同)。对此的任何建议将不胜感激。
客户代码:
public class ClientOrig {
public static void main( String[] args ) {
// Complain if we don't get the right number of arguments.
if ( args.length != 1 ) {
System.out.println( "Usage: Client <host>" );
System.exit( -1 );
}
try {
// Try to create a socket connection to the server.
Socket sock = new Socket( args[ 0 ], ServerOriginal.PORT_NUMBER );
// Get formatted input/output streams for talking with the server.
DataInputStream input = new DataInputStream( sock.getInputStream() );
DataOutputStream output = new DataOutputStream( sock.getOutputStream() );
// Get a username from the user and send it to the server.
Scanner scanner = new Scanner( System.in );
System.out.print( "Username: " );
String name = scanner.nextLine();
output.writeUTF( name );
output.flush();
byte[] challenge = ServerOriginal.getMessage( input );
System.out.println(challenge);
String request = "";
System.out.print( "cmd> " );
// We are done communicating with the server.
sock.close();
} catch( IOException e ){
System.err.println( "IO Error: " + e );
}
}
}
服务器代码:
public static byte[] getMessage( DataInputStream input ) throws IOException {
int len = input.readInt();
byte[] msg = new byte [ len ];
input.readFully( msg );
System.out.println("Read: " + msg + " which is " + msg.length);
System.out.println("Byte to string: " + new String(msg));
return msg;
}
/** Function analogous to the previous one, for sending messages. */
public static void putMessage( DataOutputStream output, byte[] msg ) throws IOException {
output.writeInt(msg.length);
output.write( msg, 0, msg.length );
System.out.println("Writing: "+ msg + " which is " + msg.length);
output.flush();
}
/** Function to handle interaction with a client. Really, this should
be run in a thread. */
public void handleClient( Socket sock ) {
try {
// Get formatted input/output streams for this thread. These can read and write
// strings, arrays of bytes, ints, lots of things.
DataOutputStream output = new DataOutputStream( sock.getOutputStream() );
DataInputStream input = new DataInputStream( sock.getInputStream() );
// Get the username.
String username = input.readUTF();
System.out.println(username);
// Make a random sequence of bytes to use as a challenge string.
Random rand = new Random();
byte[] challenge = new byte [ 16 ];
System.out.println(challenge);
rand.nextBytes( challenge );
System.out.println(challenge);
putMessage(output, challenge);
// Send the client the challenge.
putMessage( output, challenge );
getMessage(input);
} catch ( IOException e ) {
System.out.println( "IO Error: " + e );
} finally {
try {
// Close the socket on the way out.
sock.close();
} catch ( Exception e ) {
}
}
}