我正在学习一些基本的Java网络知识,并且试图使我学到的东西变为现实,因此,当我在同一台计算机上运行服务器和客户端类时,它可以正常运行,但是当我将客户端项目转移到另一个计算机上时计算机并在运行服务器后运行项目,它将冻结并打印连接超时语句。这是我的服务器代码package sample;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;import java.io.DataInputStream;import java.io.DataOutputStream;import java.net.ServerSocket;import java.net.Socket;import java.util.Date;public class Main extends Application { @Override public void start(Stage primaryStage) throws Exception{ TextArea ta = new TextArea(); primaryStage.setTitle("server"); primaryStage.setScene(new Scene(new ScrollPane(ta), 450, 200)); primaryStage.show(); new Thread(()->{ try { ServerSocket ss = new ServerSocket(8000); Platform.runLater(() -> ta.appendText("Server started at " + new Date() + '\n')); Socket s = ss.accept(); DataInputStream inputFromClient = new DataInputStream(s.getInputStream()); DataOutputStream outputToClient = new DataOutputStream(s.getOutputStream()); while (true) { double radius = inputFromClient.readDouble(); double area = radius * radius * Math.PI; outputToClient.writeDouble(area); Platform.runLater(() -> { ta.appendText("Radius received from client: " + radius + '\n'); ta.appendText("Area is: " + area + '\n'); }); } } catch (Exception e){ e.printStackTrace(); } }).start(); }public static void main(String[] args) { launch(args);}}
2 回答

杨__羊羊
TA贡献1943条经验 获得超7个赞
在服务器类中,您可以在端口8000上创建一个服务器套接字,这对于内部和外部连接均适用。但是,您的客户端类尝试创建没有给定IP地址的套接字
Socket socket = new Socket("server IP address", 8000);
通过传递字符串“服务器ip地址”,实际上是在告诉Java查找本地服务器,因为您没有传递正确的IP地址。
因此,当两个类都在同一系统上运行时,端口就很重要,但是您需要标识服务器的IP地址,以便客户端知道如果它们不在同一系统上,则在哪里寻找其连接。
添加回答
举报
0/150
提交
取消