Sending and Receiving 2D Arrays java

2019-02-20 05:24发布

What I would like to achieve by asking this question is to learn how to send and receive 2-Dimensional Arrays to another computer.

The context is that the 2-D Array is the map for my game, and when I start my game, I would like an option to be a server or client(if client, specify the server IP) and then the server would send the client (One of which would be another person, with a different IP) the 2D array when they connect.

I hope this all makes sense, I have given this ago but I couldn't get it working, I have tried with Datagram Packets, but I couldn't figure out how to send all the 2D array in segments, and then turn it back into a 2D array.

What type of Stream or general networking object do I need to use? And will it be-able to send the 2D array? Can you give an example to help me set it up?

Also to note, I will afterwards be sending Player Coordinates and Map Changes, so If the Networking object works with that too, then that's a plus.

2条回答
劫难
2楼-- · 2019-02-20 06:01

You should create an object out of it. It´s easier to handle afterwards.
After that you serialize it, then you split it in smaller byte[] (if it´s bigger then 64 kb). You add some bytes to each packet, I prefer
byte[0] = is splited?
byte[1] + byte[2] = sendNumber (just for controlling, it increases after every sent object)
byte[3] = how many parts your object has
byte[4] = what part is it
What you need else.
Afterwards you can easily put the parts together.
I have never used it but i also found a library know as kryonet (while googling).
Have a look... google it properly.

查看更多
forever°为你锁心
3楼-- · 2019-02-20 06:16

This will work with any primitive type arrays and Object arrays if object type is instanceof Serializable

server

    ServerSocket ss = new ServerSocket(port);
    Socket s = ss.accept();
    ObjectInputStream is = new ObjectInputStream(s.getInputStream());
    byte[][] array = (byte[][])is.readObject();

client

    byte[][] array = new byte[10][10];
    Socket s = new Socket("host", port);
    ObjectOutputStream os = new ObjectOutputStream(s.getOutputStream());
    os.writeObject(array);
查看更多
登录 后发表回答