Java 网络通信不是´;行不通

Java 网络通信不是´;行不通,java,networking,Java,Networking,我做了一个小游戏。现在我想从我的服务器获得高分。客户端上的代码: private int getOnlineHighscore() { int highscore = 0; try { socket = new Socket("localhost", 444); input = socket.getInputStream(); System.out.println(input); highscore

我做了一个小游戏。现在我想从我的服务器获得高分。客户端上的代码:

        private int getOnlineHighscore() {
    int highscore = 0;
    try {
        socket = new Socket("localhost", 444);
        input = socket.getInputStream();
        System.out.println(input);
        highscore = input.read();
        input.close();
        socket.close();
        input = null;
        socket = null;
    } catch (Exception e) {
        System.out.println("Verbindung fehlgeschlagen!");
    }
    System.out.println(highscore);
    return highscore;
}
在服务器上:

import java.io.*;
import java.net.*;

 public class ReadServer extends Thread {
 private Socket socket;

public ReadServer(Socket socket) {
    super();
    this.socket = socket;
}

public void run() {
    try {
        System.out.println(socket.getInetAddress());
        String result = "";
        try (BufferedReader br = new BufferedReader(
                new FileReader(System.getProperty("user.home") + "/AppData/Roaming/GameServer/.sg"))) {
            StringBuilder sb = new StringBuilder();
            String line = br.readLine();
            System.out.println("2");
            while (line != null) {
                sb.append(line);
                sb.append(System.lineSeparator());
                line = br.readLine();
            }
            System.out.println("3");
            result = sb.toString();
            System.out.println("3.5");
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        System.out.println("4");
        socket.getOutputStream().write(Integer.parseInt(result));
        System.out.println(result);
    } catch (Exception e) {
    }

    try {
        socket.close();
    } catch (Exception e) {
    }
}

public static void main(String[] Args) {
    Socket socket = null;
    ServerSocket server = null;
    try {
        server = new ServerSocket(444);
        while (true) {
            socket = server.accept();
            new ReadServer(socket).start();
        }
    } catch (Exception e) {
    }

    try {
        server.close();
    } catch (Exception e) {
    }
}
}
如果我运行它,客户端函数将返回: -1 服务器在控制台中写入(我认为不重要): /127.0.0.1 2. 3. 3.5 四,

如何解决这个问题?我想将存储在服务器上的int发送到客户端


-Jakob

-1
read()返回。
要指定流结束,请确保返回要读取的数据。

文件中存储的高分是多少?我相信该文件是空的,并且在解析整数时失败,但是由于catch块是空的,您没有看到异常。将printStacktrace或rethrow放入


另一个问题是OutputStream只发送字节,因此
write
方法只发送低8位。在客户端发送int-wrap流和
DataInputStream

-1出现在流的末尾。发送结果后执行br.reset()。它会重置流,你应该知道,它不工作了,同样的问题。我的错。我没看懂整个问题。要发送基本数据类型,应使用DataOutputStream。文件内容仅在一行中为“104”。不应该至少还点什么吗?如果我添加System.out.println(结果);对于我的服务器,它在控制台中写入“104”。它是否以新行结尾?在传递给parseInt之前,尝试调用trim()。同时打印例外,这肯定会给你一个线索。谢谢,trim()带来了不同!