我的任务是创建一个服务器,该服务器模拟计算器,并且在遇到“ +”,“-”,“ *”和“ /”以外的其他操作时,会向客户端抛出异常。 但我不知道如何将服务器中生成的异常发送给客户端。
最初,我天真的认为我可以通过catch块中的dout.writeUTF(e.getMessage())轻松地做到这一点。
package networking;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.PrintWriter;
import java.net.*;
class OperationDeniedException extends Exception {
private String op;
public OperationDeniedException(String op) {
this.op = op;
// TODO Auto-generated constructor stub
}
public String toString() {
return "OperationDeniedException: Operation " + op + " is Denied by server";
}
}
public class CalcServer {
public static void main(String[] args) {
String opr, op1, op2;
double Dop1, Dop2;
boolean divbyzero = false;
DataInputStream din;
DataOutputStream dout;
PrintWriter p;
try {
ServerSocket ss = new ServerSocket(4444);
Socket s = ss.accept();
din = new DataInputStream(s.getInputStream());
dout = new DataOutputStream(s.getOutputStream());
p = new PrintWriter(s.getOutputStream());
dout.writeUTF(opmsg);
opr = din.readUTF();
System.out.println(opr);
try {
System.out.println("Inside try for custom exception");
if (opr.charAt(0) != '+' && opr.charAt(0) != '-' && opr.charAt(0) != '*' && opr.charAt(0) != '/') {
throw new OperationDeniedException(opr);
}
} catch (OperationDeniedException e) {
String msge = e.getMessage();
System.out.println("just before write");
dout.writeUTF((String) e.toString());
System.out.println("exception sent");
System.exit(0);
}
dout.writeUTF("Send the first Operand");
op1 = din.readUTF();
Dop1 = Double.parseDouble(op1);
dout.writeUTF("Send the Second Operand");
op2 = din.readUTF();
Dop2 = Double.parseDouble(op2);
switch (opr) {
case "+":
Dop1 += Dop2;
break;
case "-":
Dop1 -= Dop2;
break;
case "*":
Dop1 *= Dop2;
break;
case "/":
if (Dop2 == 0.0) {
divbyzero = true;
break;
}
Dop1 /= Dop2;
break;
default:
break;
}
if (divbyzero) {
dout.writeUTF("Second operand is 0 and can't divide bt zero");
}
dout.writeUTF("Ans of the operation is= " + Double.toString(Dop1));
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
static final String opmsg = "Select one of the following operations +, -, *, /.";
}
答案 0 :(得分:0)
因此解决方案是在我的范围内移动我的自定义异常的catch块 通过执行dout.writeUTF(e.getMessage());将DataOutputStream对象发送到客户端的消息 对不起我浪费时间的人们。 如果有更好的方法,请发表。