2 ll jackie LL_Jackie 于 2016.04.10 11:51 提问

初学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();
            }
        }
    }
} 

6个回答

LL_Jackie
LL_Jackie   2016.04.13 17: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();
            }
        }
    }
}
CSDNXIAOD
CSDNXIAOD   2016.04.10 12:02

Java 网络编程 服务器Socket
----------------------biu~biu~biu~~~在下问答机器人小D,这是我依靠自己的聪明才智给出的答案,如果不正确,你来咬我啊!

qq_34606099
qq_34606099   2016.04.10 12:09

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

qq_34606099
qq_34606099   2016.04.10 12:12

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

qq_34606099
qq_34606099   2016.04.10 12:15

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

LL_Jackie
LL_Jackie 多客户端服务器,根据书上写的
一年多之前 回复
LL_Jackie
LL_Jackie 这是一道题,需要写GUI界面的,怎么设置等待?
一年多之前 回复
qq_34606099
qq_34606099   2016.04.10 12: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();
    }
}
LL_Jackie
LL_Jackie 你这个和我的代码区别在哪?还是没找到问题啊
一年多之前 回复
Csdn user default icon
上传中...
上传图片
插入图片
准确详细的回答,更有利于被提问者采纳,从而获得C币。复制、灌水、广告等回答会被删除,是时候展现真正的技术了!