简体   繁体   中英

DataOutputStream- Always writing to server?

For the purposes of a simple 2D game, I need my client program to always be sending coordinates to a server.

So, I created a test to see if I could make both players have the same velocity by sending and retrieving values from the server.

package main;

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;

public class DataSender implements Runnable{

    private DataInputStream fromServer;
    private DataOutputStream toServer; 

    Player player;
    Player opponent;

    public DataSender(DataInputStream fromServer, DataOutputStream toServer, Player player, Player opponent){

        this.fromServer = fromServer;
        this.toServer = toServer; 

        this.player = player;
        this.opponent = opponent;   
    }

    @Override
    public void run() {

        while(true){

                try {
                    toServer.writeInt(player.velX);
                } catch (IOException e) {
                    e.printStackTrace();
                }

                try {
                    opponent.velX = fromServer.readInt();
                } catch (IOException e) {
                    e.printStackTrace();
                }
        }   
    }
}

The while(true) loop only executes one time upon thread creation. How can I establish a constant stream of data?

Your readInt function is probably blocking. If the server doesn't reply to the client with the opponents position, then the loop will stop until 4 bytes are received from the server.

Or, it could be the writeInt call. Be sure to disable Nagle's algorithm. It will cause undue latency with such small amounts of data being sent. In Java, its referred to as TCP_NODELAY . This could also be what's wrong with the code, the bytes you are writing are not being sent because there's not enough data being written to cause transmission.

Even better, use UDP instead, if you're entirely open to suggestion here. UDP is typically used in game programming because the data involved is real time, and is only useful for a short period of time. TCP slows this down because you might be acknowledging packets, or waiting to receive packets you no longer care about because they are too old. UDP gives you control over that.

Also, typically there's a thread used for sending, and a thread for receiving in networking code. I suggest you create 2 threads so you don't have this kind of problem.

In this situation, I recommend using a separate thread for your writing of data. For instance, when the velocity changes via user input, send the velocity/location packet. Use a thread like this to constantly read(and block) for the velocity/position of the opponent.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM