我正在使用密码验证应用程序。为了进行测试,我想将示例ID从键盘发送到服务器,服务器将确认收到该示例ID。但是,当我发送请求时,服务器没有响应。错误在哪里?
public class Client {
public static void main(String args[]) {
Scanner scanner = new Scanner(System.in);
try {
Socket skt = new Socket("localhost", 2011);
BufferedReader br = new BufferedReader(
new InputStreamReader(skt.getInputStream()));
System.out.print("Received: " + br.readLine());
PrintWriter pw =
new PrintWriter(skt.getOutputStream(), true);
int key_in=scanner.nextInt();
System.out.println("Sent: " +key_in);
pw.print(key_in);
pw.close();
br.close();
}
catch(Exception e) {
System.out.print("Error");
}
}
}
public class Server {
public static void main(String args[]) {
String input = "Enter ID";
ArrayList<String> passwords = new ArrayList<String>();
passwords.add("password1");
passwords.add("password2");
passwords.add("password3");
try {
ServerSocket srvr = new ServerSocket(2011);
System.out.println("Server running...");
Socket skt = srvr.accept();
System.out.println("Client connected");
PrintWriter pw =
new PrintWriter(skt.getOutputStream(), true);
System.out.println("Sent: " + input);
BufferedReader br = new BufferedReader(
new InputStreamReader(skt.getInputStream()));
System.out.println("Received:" + br.readLine());
pw.print(input);
pw.close();
br.close();
skt.close();
srvr.close();
}
catch(Exception e) {
System.out.println("Error");
}
}
}
如果您不介意,我对您的代码进行了很少的更改。换矿最好使用DataInputStream/DataOutputStream
。我不知道PrintWriter
的问题在哪里,但是其中一个问题在那里,我不确定在哪里。如果您愿意-您可以自由地找到它。第二个问题是您打印了向Socket写的东西,但实际上您没有:
System.out.println("Received:" + br.readLine());
pw.print(input);
您正在尝试在实际将输入发送给客户端之前读取值。
public class Server {
public static void main(String[] args) {
String input = "Enter ID";
ArrayList<String> passwords = new ArrayList<>();
passwords.add("password1");
passwords.add("password2");
passwords.add("password3");
try {
ServerSocket srvr = new ServerSocket(2011);
System.out.println("Server running...");
Socket skt = srvr.accept();
System.out.println("Client connected");
DataOutputStream pw = new DataOutputStream(skt.getOutputStream());
DataInputStream br = new DataInputStream(skt.getInputStream());
System.out.println("Sent: " + input);
pw.writeUTF(input);
pw.flush();
System.out.println("Received:" + br.readUTF());
pw.close();
br.close();
skt.close();
srvr.close();
}
catch(Exception e) {
e.printStackTrace();
}
}
}
public class Client {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
try {
Socket skt = new Socket("localhost", 2011);
DataInputStream br = new DataInputStream(skt.getInputStream());
DataOutputStream pw = new DataOutputStream(skt.getOutputStream());
System.out.print("Received: " + br.readUTF());
int key_in=scanner.nextInt();
System.out.println("Sent: " +key_in);
pw.writeInt(key_in);
pw.close();
br.close();
}
catch(Exception e) {
e.printStackTrace();
}
}
}
希望这会对您有所帮助,您将使用我的更改来查找代码中的错误。