如何同时从标准输入和套接字读取数据(java多线程套接字编程)
此程序向用户提示三个选项:如何同时从标准输入和套接字读取数据(java多线程套接字编程),java,multithreading,sockets,Java,Multithreading,Sockets,此程序向用户提示三个选项: Enter an option ('m', 'f', 'x'): (M)essage (send) (F)ile (request) e(X)it 我只想关注“M”和“M”选项。(不允许为此添加“接收”选项) 代码运行的屏幕截图(服务器端错误): 代码运行的屏幕截图(成功的客户端): 问题在于缓冲读取器readStandardInput和 BufferedReader readFromClient无法同时执行(或至少同时读取同一行代码)。我想知道
Enter an option ('m', 'f', 'x'):
(M)essage (send)
(F)ile (request)
e(X)it
我只想关注“M”和“M”选项。(不允许为此添加“接收”选项)
代码运行的屏幕截图(服务器端错误):
代码运行的屏幕截图(成功的客户端):
问题在于
缓冲读取器readStandardInput
和
BufferedReader readFromClient
无法同时执行(或至少同时读取同一行代码)。我想知道如何使它们同时执行
代码:
我的问题是:
如何使第一个屏幕截图中的服务器能够输入选项“m”,同时从客户端套接字读取一行内容 Java标准输入流和
Java.net.Socket
正在阻塞(因此,一旦您在Socket.getInputStream
或系统上调用read
。在
中,您的应用程序将等待接收到某个内容),这意味着您无法在同一线程中同时执行这些内容的读取
如果您设置了另一个线程为客户端连接提供服务,那么您将能够在等待控制台输入时从客户端接收数据
try{
OutputOptions();
String sendingMessage = "";
BufferedReader readFromClient = null;
String fromClient = "";
if(isConnected == true){
readFromClient = new BufferedReader(new InputStreamReader(socket.getInputStream()));
fromClient = readFromClient.readLine();
System.out.println("Recieved from client: " + fromClient);
//The 4 lines above this comment are recieving a message from the client
//the lines below this comment are reading from standard input
//I want to be able to do both the above and the below lines at the same time (reading two types of input, standard and socket),
//In other words, once the client sends a message after typing "m",
//it should appear on the server side, but if i decide to type "m" first
//on the server side, then the client will also have to be able to
//read that message, then afterwards be able to take in standard input
BufferedReader readStandardInput = new BufferedReader(new InputStreamReader(System.in));
option = readStandardInput.readLine();
if (option.length() == 1){
if(option.equals("m") || option.equals("M")){
System.out.println("Enter your message: ");
StandardOutput();
}
if(option.equals("m") || option.equals("M")){
System.out.println("Enter your message: ");
StandardOutput();
}
if(option.equals("f") || option.equals("F")){
FileTransferReceive();
}
if(option.equals("x") || option.equals("X")){
System.exit(0);
}
else{
StandardOutput();
}
}
else{
StandardOutput();
}
}
//}
}catch (IOException e){
e.printStackTrace();
}
finally{ }