我正在编写用于练习设置服务器的代码,但是当我设置输入和输出流时,它说我必须抓住IO Exception
。但是,我已经抓住了这个例外。这是代码:
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package server;
import java.io.*;
import java.net.*;
import java.util.Date;
import javafx.application.Application;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.layout.StackPane;
import javafx.stage.Stage;
import javafx.application.Platform;
import javafx.scene.control.ScrollPane;
import javafx.scene.control.TextArea;
/**
*
*
*/
public class Server extends Application {
@Override
public void start(Stage primaryStage) {
TextArea ta = new TextArea();
Scene scene = new Scene(new ScrollPane(ta), 450, 200);
primaryStage.setTitle("Server");
primaryStage.setScene(scene);
primaryStage.show();
new Thread(() ->
{
try
{
ServerSocket serversocket = new ServerSocket(8000);
Platform.runLater(() -> {
ta.appendText("Server started at " + new Date() + '\n');
Socket socket = serversocket.accept();
DataInputStream inputFromClient = new DataInputStream(socket.getInputStream());
DataOutputStream outputToClient = new DataOutputStream(socket.getOutputStream());
while(true)
{
double radius = inputFromClient.readDouble();
double area = Math.PI* radius * radius;
outputToClient.writeDouble(area);
Platform.runLater(() -> {
ta.appendText("Radius received from client: " + radius
+ '\n');
ta.appendText("Area is: " + area + '\n');
});
}
});
}
catch(IOException ex)
{
ex.printStackTrace();
}
}).start();
}
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
launch(args);
}
}
第一次调用可能引发异常的方法时,在设置服务器套接字时,IDE上没有检测到错误。但是,下一次,当我尝试设置套接字时,以及随后可能发生异常的所有时间,IDE都说我需要捕获异常,即使我认为因为它全部在try / catch块中,它已经被抓住了。谢谢你的帮助。