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

初学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 生物医学数据分析。基础课程就v经常唱课程舅成牛逼
  • ¥15 云环境云开发云函数对接微信商户中的分账功能
  • ¥15 空间转录组CRAD遇到问题
  • ¥20 materialstudio计算氢键脚本问题
  • ¥15 有没有代做有偿主要做数据可视化部分即可(2023全国高考更省一本线理科类)
  • ¥15 配置FPT报错,该如何处理
  • ¥15 请大家看一下这个代码咋写,一点思路都没有,最好能做一下,不要伪代码,有偿
  • ¥15 有偿请人帮写个安卓系统下禁止装软件及禁止拷入文件的程序
  • ¥100 用 H.265 对音视频硬编码 (CUDA)