LL_Jackie 2016-04-10 03:51 采纳率: 100%
浏览 1868
已采纳

初学Java网络编程socket,为何我的服务器打不开?

初学Java网络编程socket,写了个服务器,但是打不开,求指导。代码如下

 import java.io.*;
import java.net.*;
import java.util.*;
import javafx.application.Application;
import javafx.application.Platform;
import javafx.scene.Scene;
import javafx.scene.control.ScrollPane;
import javafx.scene.control.TextArea;
import javafx.stage.Stage;

public class Test2_2Server extends Application{
    //创建显示文本域
    private TextArea area = new TextArea();

    public void start(Stage primaryStage){
        area.setEditable(false);

        Scene scene = new Scene(new ScrollPane(area), 450,300);
        primaryStage.setTitle("Test2_2Server");
        primaryStage.setScene(scene);
        primaryStage.show();

        try {
            //创建一个服务器套接字
            ServerSocket serverSocket = new ServerSocket(8800);
            Platform.runLater(() ->
                area.appendText("Server started at " + new Date() + '\n'));

            int clientNo = 1;
            while (true){
                //监听
                Socket socket = serverSocket.accept();

                area.appendText("Starting thread for client " + clientNo + " at " + new Date() + '\n');

                //获取客户端地址
                InetAddress inetAddress = socket.getInetAddress();
                area.appendText("Client " + clientNo + "'s host name is " + inetAddress.getHostName() + '\n');
                area.appendText("Client " + clientNo + "'s IP Address is " + inetAddress.getHostAddress() + '\n');

                //创建进程
                HandleAClient task = new HandleAClient(socket);

                //开始运行
                new Thread(task).start();

                //客户端数加一
                clientNo++;
            }
        }
        catch(IOException ex) {
            System.err.println(ex);
        }


    }

    public static void main(String[] args) {
        launch(args);
    }

    //服务器端的任务类
    class HandleAClient implements Runnable{
        private Socket socket;

        public HandleAClient(Socket socket1){
            this.socket = socket1;
        }

        public void run(){
            try {
                //创建输入输出流
                DataInputStream inputFromClient = new DataInputStream(socket.getInputStream());
                DataOutputStream outputToClient = new DataOutputStream(socket.getOutputStream());

                while (true){
                    //获取客户端数据
                    double annualInterestRate = inputFromClient.readDouble();
                    int numberOfYears = inputFromClient.readInt();
                    double loanAmount = inputFromClient.readDouble();

                    //计算偿还额
                    double totalPayment = loanAmount * Math.pow(1 + annualInterestRate * 0.01, numberOfYears);
                    double monthlyPayment = totalPayment / numberOfYears / 12;
                    //将数据传送至客户端
                    outputToClient.writeDouble(monthlyPayment);
                    outputToClient.writeDouble(totalPayment);
                    //输出
                    Platform.runLater(() ->{
                        area.appendText("Annual Interest Rate:" + annualInterestRate + '\n');
                        area.appendText("Number Of Year:" + numberOfYears + '\n');
                        area.appendText("Loan Amount:" + loanAmount + '\n');

                        area.appendText("Monthly Payment:" + monthlyPayment + '\n');
                        area.appendText("Total Payment:" + totalPayment + '\n');
                    });
                }
            }
            catch (IOException ex) {
                ex.printStackTrace();
            }
        }
    }
} 
  • 写回答

5条回答 默认 最新

  • LL_Jackie 2016-04-13 09:02
    关注

    已经找到问题,问题出在JavaFX的application线程,需要给服务器也分配一个线程,否则两者会发生冲突,导致程序无法正常启动。
    具体修改程序代码如下,由于有人说看起来太复杂,稍作删减:

    import java.io.*;
    import java.net.*;
    import java.util.*;
    import javafx.application.Application;
    import javafx.application.Platform;
    import javafx.scene.Scene;
    import javafx.scene.control.ScrollPane;
    import javafx.scene.control.TextArea;
    import javafx.stage.Stage;
    
    public class net extends Application{
        //创建显示文本域
        private TextArea area = new TextArea();
    
        public void start(Stage primaryStage){
    
            Scene scene = new Scene(new ScrollPane(area), 450,300);
            primaryStage.setTitle("Test2_2Server");
            primaryStage.setScene(scene);
            primaryStage.show();
    
        //此处做修改,为服务器分配线程
            new Thread(() ->{
                try {
                    //创建一个服务器套接字
                    ServerSocket serverSocket = new ServerSocket(8000);
    
                    area.appendText("Server started at " + new Date() + '\n');
    
                    while (true){
    
                        //监听
                        Socket socket = serverSocket.accept();
    
                        //创建进程
                        HandleAClient task = new HandleAClient(socket);
    
                        //开始运行
                        new Thread(task).start();
    
                    }
                }
                catch(IOException ex) {
                    System.err.println(ex);
                }
            }).start();
    
    
        }
    
        public static void main(String[] args) {
            launch(args);
        }
    
        //服务器端的任务类
        class HandleAClient implements Runnable{
            private Socket socket;
    
            public HandleAClient(Socket socket1){
                this.socket = socket1;
            }
    
            public void run(){
                try {
                    //创建输入输出流
                    DataInputStream input = new DataInputStream(socket.getInputStream());
                    DataOutputStream output = new DataOutputStream(socket.getOutputStream());
    
                    while (true){
                        //获取客户端数据
                        double annualInterestRate = input.readDouble();
                        int numberOfYears = input.readInt();
                        double loanAmount = input.readDouble();
    
                        //计算偿还额
                        double totalPayment = loanAmount * Math.pow(1 + annualInterestRate * 0.01, numberOfYears);
                        double monthlyPayment = totalPayment / numberOfYears / 12;
                        //将数据传送至客户端
                        output.writeDouble(monthlyPayment);
                        output.writeDouble(totalPayment);
                        //输出
                        Platform.runLater(() ->{
                            area.appendText("Annual Interest Rate:" + annualInterestRate + '\n');
                            area.appendText("Number Of Year:" + numberOfYears + '\n');
                            area.appendText("Loan Amount:" + loanAmount + '\n');
    
                            area.appendText("Monthly Payment:" + monthlyPayment + '\n');
                            area.appendText("Total Payment:" + totalPayment + '\n');
                        });
    
    
                    }
                }
                catch (IOException ex) {
                    ex.printStackTrace();
                }
            }
        }
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(4条)

报告相同问题?

悬赏问题

  • ¥15 微信公众号如何开发网页
  • ¥15 h3.6m 人类行为预测论文复现
  • ¥50 wordpress项目注册报失败刷新后其实是成功状态,请求排查原因
  • ¥20 linxu服务器僵尸进程不释放,代码如何修改?
  • ¥15 pycharm激活不成功
  • ¥40 如果update 一个列名为参数的value
  • ¥15 基于51单片机的水位检测系统设计中LCD1602一直不显示
  • ¥15 OCS2安装出现问题,请大家给点意见
  • ¥15 ros小车启动launch文件报错
  • ¥15 vs2015到期想登陆但是登陆不上