gpt4 book ai didi

java - 客户端无法向服务器发送第二次执行

转载 作者:行者123 更新时间:2023-12-01 10:00:17 26 4
gpt4 key购买 nike

我有一个 Java 的服务器客户端程序。服务器进行一些基本计算并将结果发送给客户端。在此之前,客户端必须发送操作和值。我可以成功运行一次,但是当我插入第二个操作和值时,我得到 null 的结果。为什么会出现这种情况?

服务器

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;

public class Server {

private static final int PORT = 9001;

public static void main(String[] args) throws IOException {
// TODO Auto-generated method stub
System.out.println("O servidor está a correr...");
ServerSocket listener = new ServerSocket(PORT);
listener.setSoTimeout(0);
try{
while(true){
new Handler(listener.accept()).start();
}
}finally{
listener.close();
System.out.println("Servidor fechou!");
}
}

private static class Handler extends Thread{
private Socket socket;
private BufferedReader in;
private PrintWriter out;

public Handler(Socket socket){
this.socket = socket;
}

public void run(){
try{
in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
out = new PrintWriter(socket.getOutputStream(), true);
while(true){
String line = in.readLine();
System.out.print(line);
double result = parseExecution(line);
out.write("" + result + "\n");
out.close();
in.close();
}
}catch(IOException e){
e.printStackTrace();
}
out.flush();


}

private double parseExecution(String line) throws IllegalArgumentException{
// TODO Auto-generated method stub
double result = 0;
String [] elements = line.split(":");
if (elements.length != 3){
throw new IllegalArgumentException("parsing error!");
}
double firstValue = 0;
double secondValue = 0;
try{
firstValue = Double.parseDouble(elements[1]);
secondValue = Double.parseDouble(elements[2]);
} catch(Exception e){
throw new IllegalArgumentException("Invalid arguments!");
}
switch (elements[0].charAt(0)) {
case '+':
result = firstValue + secondValue;
break;
case '-':
result = firstValue - secondValue;
break;
case '*':
result = firstValue * secondValue;
break;
case '/':
if(secondValue != 0)
result = firstValue / secondValue;
break;
default:
throw new IllegalArgumentException("Invalid math operation!");
}
return result;
}
}
}

客户端

import java.io.*;
import java.net.Socket;
import java.net.UnknownHostException;

import javax.swing.JOptionPane;
import javax.xml.bind.helpers.ParseConversionEventImpl;

public class MathClient {

private String getServerAddress(){
return JOptionPane.showInputDialog("Introduza IP do Servidor", JOptionPane.QUESTION_MESSAGE);
}

private void run() throws IOException {
String serverAddress = getServerAddress();
int port = 9001;

// criar a socket

Socket socket = new Socket(serverAddress, port);
BufferedReader reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
BufferedReader op = new BufferedReader(new InputStreamReader(System.in));
BufferedReader valor1 = new BufferedReader(new InputStreamReader(System.in));
BufferedReader valor2 = new BufferedReader(new InputStreamReader(System.in));
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
while(true){
System.out.println("Operação(+,-,*,/): ");
String operacao = op.readLine();
System.out.println("Primeiro valor: ");
String primeiroValor = valor1.readLine();
System.out.println("Segundo valor: ");
String segundoValor = valor2.readLine();
writer.write(operacao+":"+primeiroValor+":"+segundoValor);
writer.newLine();
writer.flush();
//double resultado = Double.parseDouble(reader.readLine());
System.out.println(reader.readLine());

}

}

public static void main(String[] args) throws UnknownHostException, IOException {
MathClient client = new MathClient();
client.run();
}

}

谢谢!

编辑:在 run() 方法中我正在执行一个 while 循环。但现在我收到一条错误消息,提示“流已关闭”。当我尝试将 in.close() 放在 while 循环之外时,它给了我另一个错误并删除了 in.close()

java.io.IOException: Stream closed
at java.io.BufferedReader.ensureOpen(Unknown Source)
at java.io.BufferedReader.readLine(Unknown Source)
at java.io.BufferedReader.readLine(Unknown Source)
at MathFinal.Server$Handler.run(Server.java:41)

第 41 行是:String line = in.readLine();

最佳答案

我修复了您的代码,它可以使用 Java 7 try-with-resources 运行。这是重要的片段:

private static class Handler extends Thread{
private Socket socket;

public Handler(Socket socket){
this.socket = socket;
}

public void run(){
try(BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
PrintWriter out = new PrintWriter(socket.getOutputStream(), true)) {
while(true){
String line = in.readLine();
System.out.print(line);
double result = parseExecution(line);
out.write("" + result + "\n");
out.flush();
}
}catch(IOException e){
e.printStackTrace();
}

}

这样做,您无需担心自己关闭资源。

关于java - 客户端无法向服务器发送第二次执行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36863232/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com