定义DataOutputStream和DataInputStream变量的问题

时间:2017-04-24 00:17:35

标签: java networking

我出于某种原因无法使用out,in和inUTF变量。 我尝试在不同的地方定义它们并以不同的方式使用它们,我似乎无法找到解决方案。这是我的代码。

public class Server {

static ServerSocket serverSocket;
static Socket socket;
static DataOutputStream out;
static DataInputStream in;
static boolean running = false;

static int playerX;
static int playerY;
static int playerZ;

static String[] arrayX;
static String[] arrayY;
static String[] arrayZ;

static String inUTF;

public static void main(String args[]) throws Exception {
    running = true;
    System.out.println("Starting server");
    serverSocket = new ServerSocket(7877);
    System.out.println("Finished");

    out = new DataOutputStream(socket.getOutputStream());
    in = new DataInputStream(socket.getInputStream());
    inUTF = in.readUTF();

    while (running) {
        tick();
    }

}

public static void tick() {
    try {

        try {
            socket = serverSocket.accept();
        } catch (Exception e) {
            System.out.println("Something went wrong in the tick() loop: Could not accept client connection");
        }

        if (inUTF.startsWith("X")) {
            arrayX = inUTF.split(":");
            playerX = Integer.parseInt(arrayX[1]);
            out.writeUTF("X:" + playerX);

        } else if (inUTF.startsWith("Y")) {
            arrayY = inUTF.split(":");
            playerY = Integer.parseInt(arrayY[1]);
            out.writeUTF("Y:" + playerY);

        } else if (inUTF.startsWith("Z")) {
            arrayZ = inUTF.split(":");
            playerZ = Integer.parseInt(arrayZ[1]);
            out.writeUTF("Z:" + playerZ);

        } else {
            System.out.println("Something went wrong in the tick() loop: Did not receive a player position");
        }

    } catch (Exception e) {
        System.out.println("Something went wrong in the tick() loop");
    }
}

0 个答案:

没有答案