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

初学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
    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();
                }
            }
        }
    }
    
    点赞 评论
  • qq_34606099
    放开那只肥鸡 2016-04-10 04:09

    你确定你的代码没报错?为何我复制你的代码一堆报错!

    点赞 评论
  • qq_34606099
    放开那只肥鸡 2016-04-10 04:12

    开个多线程而已你搞的这么复杂! 还搞了个类!好多局部变量引用其他类变量报错,还有最上面while方法!等待的时候给他个线程去等待啊!

    点赞 评论
  • qq_34606099
    放开那只肥鸡 2016-04-10 04:15

    一个服务端没必要搞那么多类!直接一个类搞定。你那样看起来头晕都不知道你在写什么!直接就是一个类!

    点赞 评论
  • qq_34606099
    放开那只肥鸡 2016-04-10 04:55

    ServerSocket server = new ServerSocket(5000);
    while (true) {

            final Socket socket = server.accept();
            new Thread(new Runnable() {
    
                public void run() {
                    try {
    
                        InputStream in = socket.getInputStream();
                        OutputStream out = socket.getOutputStream();
                        String ip = socket.getInetAddress().getHostAddress();
    
    
                        byte[] datas = new byte[1024];
                        int len;
                        String mess;
    
                        while (true) {
                            len = in.read(datas);
                            mess = new String(datas, 0, len);
    
    
    
                            out.write(mess.toUpperCase().getBytes());
    
                            if ("bye".equals(mess)) {
                                break;
                            }
                        }
    
                    } catch (IOException e) {
                        throw new RuntimeException(e);
                    } finally {
                        try {
                            socket.close();
                        } catch (IOException e) {
                            throw new RuntimeException(e);
                        }
                    }
    
                }
            }).start();
        }
    }
    
    点赞 评论

相关推荐