我在java中编写了一个Server-Client模型程序,它在eclipse上运行得很好。但是,当我尝试通过命令行运行客户端时(在Windows 10中),我无法向stdin写任何内容(我可以在Eclipse上执行此操作)。那是为什么?
这是客户端代码(不是最好的,我知道):
import java.io.*;
import java.net.*;
public class MyEchoClient {
public static void main(String[] args) throws IOException{
Socket clientSocket = null; // the connection socket
PrintWriter out = null;
BufferedReader in = null;
String host = args[0], msg, tmp;
int port = Integer.decode(args[1]).intValue(), len;
System.out.println("Connecting to " + host + ":" + port);
try { // Trying to connect to a socket and initialize an output stream
clientSocket = new Socket(host, port); // host and port
out = new PrintWriter(new OutputStreamWriter(clientSocket.getOutputStream(), "UTF-8"), true);
} catch (UnknownHostException e) {
System.out.println("Unknown host: " + host);
System.exit(1);
} catch (IOException e) {
System.out.println("Couldn't get output to " + host + " connection");
System.exit(1);
}
try { // Initialize an input stream
in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream(),"UTF-8"));
} catch (IOException e) {
System.out.println("Couldn't get input to " + host + " connection");
System.exit(1);
}
System.out.println("Connected to server!");
BufferedReader userIn = new BufferedReader(new InputStreamReader(System.in));
try{
while(true){
while(!userIn.ready()){
if (in.ready()){ // if server has something to write, when client does'nt have something to write
tmp=in.readLine();
len=tmp.length();
System.out.print(tmp);
if ((len>0 && tmp.charAt(tmp.length()-1)=='>') || tmp.contains("UNIDENTIFIED"))
System.out.println();
}
}
System.out.println();
msg = userIn.readLine();
if (msg==null) { break; }
out.println(msg);
tmp=in.readLine();
if (tmp.contains("~")) { break; }
System.out.println(tmp);
}
}
catch(IOException e){ System.out.println("Error with server connection."); }
System.out.println("Exiting...");
out.close();
in.close();
userIn.close();
clientSocket.close();
}
}
编辑:这是我尝试使用该命令运行MyEchoClient
时获得的输入(在连接到端口4000上的服务器之后)java client.MyEchoClient 127.0.0.1 4000
:
Connecting to 127.0.0.1:4000
Connected to server!
(MyEchoClient
位于名为client
)的文件夹中
正如我所说,我不能写任何东西给stdin ...