1
我寫了一個簡單的客戶端服務器程序。我能夠從客戶端發送文本到服務器,反之亦然。但是,在客戶端上打印服務器數據後,我無法在客戶端的CLI上打印任何內容。如何在Java客戶端服務器程序中從控制檯獲取輸入
我不知道我在做什麼錯。我懷疑行中的錯誤評論爲「Bug Here」。我無法找到那些線路上有什麼問題。
請在下面找到我的代碼。
ATMClient.java
import java.io.*;
import java.net.*;
public class ATMClient
{
public static void main(String args[])
{
try
{
Socket sock = new Socket("localhost", 9010);
sock.setSoTimeout(10000);
System.out.println("Connection established");
String data = null;
InputStreamReader input = new InputStreamReader(sock.getInputStream());
BufferedReader bread = new BufferedReader(input);
BufferedReader brCli = new BufferedReader(new InputStreamReader(System.in));
System.out.print("Enter text to be sent to Server: ");
String strCli = brCli.readLine();
PrintWriter pwrite = new PrintWriter(sock.getOutputStream(), true);
pwrite.println(strCli);
// Bug Here: The control in not coming out of the while loop
while((data = bread.readLine()) != null)
{
System.out.println(data);
}
// Bug Here: The following line does not get printed.
System.out.print("Enter an Option: ");
pwrite.close();
bread.close();
input.close();
}
catch(IOException ex)
{
System.err.println(ex);
}
}
}
ATMServer.java
import java.io.*;
import java.net.*;
public class ATMServer
{
public static void main(String args[])
{
try
{
ServerSocket server = new ServerSocket(9010);
Socket client = server.accept();
System.out.println("Connection Established");
InputStream input = client.getInputStream();
BufferedReader bufread = new BufferedReader(new InputStreamReader(input));
PrintWriter pwrite = new PrintWriter(client.getOutputStream(), true);
pwrite.println("1. Deposit");
pwrite.println("2. Withdrawal");
pwrite.println("3. Balance");
pwrite.println("4. Exit");
String data = null;
while((data = bufread.readLine()) != null)
{
System.out.println(data);
}
pwrite.close();
bufread.close();
input.close();
server.close();
client.close();
}
catch(Exception ex)
{
System.err.println(ex);
}
}
}
輸出:
user1$ java ATMServer
Connection Established
hello
user1$ java ATMClient
Connection established
Enter text to be sent to Server: hello
1. Deposit
2. Withdrawal
3. Balance
4. Exit
Deposit
^C user1$
你能幫我搞清楚如何獲得客戶端的控制檯上輸入?謝謝。