java - 网络通讯无法正常工作

标签 java networking

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

        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 4

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

-雅各布

最佳答案

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

关于java - 网络通讯无法正常工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33973488/

相关文章:

java - 如何从网络项目创建 war 和 jar ?

linux - 在软件级别负载平衡 2 条 ADSL 线路

windows - 如何在 Windows Powershell 中获取网络适配器的类型(Wi-Fi、以太网、蓝牙)?

java - 将下拉值拉入整数

java - 如何在不更新旧记录的情况下使用 Hibernate session.save() 插入/保存对象

java - 哪个更快?(来自CTCI书)

java - 将 UTC 时间转换为手机本地时间

android - 如何在 Android 上检测网络类型从 3g 到 H+ 的变化

android 为什么向服务器发送信息只适用于 WIFI?

networking - TURN 服务器 XOR-RELAYED-ADDRESS IP 与其自己的公共(public) IP 不同