在服务器和客户端(Java)之间发送坐标

时间:2018-07-21 09:55:03

标签: java server client java-io flush

如何从服务器向客户端发送对象(“播放器”)的坐标?

服务器:

package it.unical.igpe.online;

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;

public class Server {
    static ServerSocket serverSocket;
    static DataOutputStream dos;
    static DataInputStream dis;
    private static boolean accepted;

    public static void initializeServer() {
        try {
            serverSocket = new ServerSocket(7777);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static void listenForServerRequest() {
        Socket socket = null;
        try {
            socket = serverSocket.accept();
            dos = new DataOutputStream(socket.getOutputStream());
            dis = new DataInputStream(socket.getInputStream());
            accepted = true;
            System.out.println("CLIENT HAS REQUESTED TO JOIN, AND WE HAVE ACCEPTED");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

连接方法:

private boolean connect() {
    try {
        socket = new Socket(ip, port);
        dos = new DataOutputStream(socket.getOutputStream());
        dis = new DataInputStream(socket.getInputStream());
        accepted = true;
    } catch (IOException e) {
        System.out.println("Unable to connect to the address: " + ip + ":" + port + " | Starting a server");
        return false;
    }
    System.out.println("Successfully connected to the server.");
    clientConnected = true;
    return true;
}

运行:

@Override
public void run() {
    if(!accepted) {
        Server.listenForServerRequest();
    }
    gameManager.startGame();
    while(!gameManager.gameOver()) {
        this.requestFocusInWindow();
        try {
            Thread.sleep(40);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        if

        gameManager.update();
        handleActions();
        this.repaint();
    }
}

我想在run方法中发送播放器(World.getPlayer1().getX() ecc..)的坐标,并更新世界的每个动作。因此,客户端和服务器可以看到另一个玩家的位置。 我应该将DataInputStream和DataOutputStream与writeInt()和readInt()一起使用吗?

0 个答案:

没有答案