发送和接收2D数组java [英] Sending and Receiving 2D Arrays java
问题描述
我想通过提出这个问题来了解如何向另一台计算机发送和接收二维数组。
What I would like to achieve by asking this question is to learn how to send and receive 2-Dimensional Arrays to another computer.
上下文是 2-D Array 是我游戏的地图,当我开始游戏时,我希望选择成为服务器或客户端(如果是客户端,请指定服务器 IP )然后服务器在连接时发送客户端(其中一个是另一个人,具有不同的 IP )2D阵列。
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.
我希望这一切都有意义,我已经给了这个,但我无法让它工作,我尝试过数据报包,但我无法想象如何分段发送所有2D数组,然后将其转换回2D数组。
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.
我需要使用哪种类型的流或一般网络对象?它能够发送2D阵列吗?
你能给我一个例子来帮我设置吗?
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.
推荐答案
这将适用于任何基本类型数组和对象数组(如果对象类型)是可序列化的实例
This will work with any primitive type arrays and Object arrays if object type is instanceof Serializable
服务器
ServerSocket ss = new ServerSocket(port);
Socket s = ss.accept();
ObjectInputStream is = new ObjectInputStream(s.getInputStream());
byte[][] array = (byte[][])is.readObject();
客户
byte[][] array = new byte[10][10];
Socket s = new Socket("host", port);
ObjectOutputStream os = new ObjectOutputStream(s.getOutputStream());
os.writeObject(array);
这篇关于发送和接收2D数组java的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!