Java套接字 – 发送对象并将对象分发到所有已连接的客户端

所以在这里,我是一个3D游戏,效果很棒……

但是,我希望让它成为多人游戏。 我对套接字很新,所以我不完全了解如何使用它们,更具体地说,如何将对象从客户端发送到服务器,然后将该对象分发给所有其他客户端。

这是我发送的对象:

public class Vector3f{ int x, y, z; public Vector3f(int x, int y, int z){ this.x = x; this.y = y; this.z = z; } } 

(这是为了玩家的位置)客户端类将创建一个新的Socket,只是我的本地IP和端口1500(例如),而服务器将创建服务器套接字到端口1500(显然)。

我只想知道如何将这个对象发送到服务器(或主机),然后服务器编辑该对象以获得不同的值,然后将其发回。 例如:

在Client类中,类似于:

 Vector3f origionalpos = new Vector3f(0,0,0); System.out.println("x: "+origionalpos.x+" y: "+origionalpos.y+" z: "+origionalpos.z); ObjectOutputStream.writeObject(origionalpos); 

然后服务器会收到这个,并在发回之前修改对象,如下所示:

 Vector3f obj = ObjectRecievedFromClient; obj.x+=10; obj.y+=10 obj.z+=10 ObjectOutputStream.writeObject(obj); //here I would also like to send to all clients who are connected. 

实际上在我的游戏中,我不会改变服务器的位置(除非我想用命令或其他东西),只是将它重新分配给其他客户端,但是我希望看到它首先工作的证据:)

最后,在Client类中,它将接收新的Position并指定另一个对象以等于从服务器接收的对象,并执行以下操作:

 Vector3f newpos = ObjectInputStream.readObject(); System.out.println("x: "+newpos.x+" y: "+newpos.y+" z: "+newpos.z); 

任何帮助都是极好的。 请记住,这还没有放到我的游戏中,所以现在只有这三个类,其中Client类有自己的main方法,Server类也是如此。

事实certificate,它很简单:

客户:

 private Socket socket = null; private ObjectInputStream inStream = null; private ObjectOutputStream outStream = null; Vector3f v3f = new Vector3f(0,0,0); 

接着:

 socket = new Socket("localHost", port); System.out.println("Player Position: " + v3f.x+","+v3f.y+","+v3f.z); outStream = new ObjectOutputStream(socket.getOutputStream()); outStream.writeObject(v3f); inStream = new ObjectInputStream(socket.getInputStream()); v3f = (Vector3f) inStream.readObject(); System.out.println("New Player Position: " + v3f.x+","+v3f.y+","+v3f.z); 

服务器:

 private ServerSocket serverSocket = null; private Socket socket = null; private ObjectInputStream inStream = null; private ObjectOutputStream outStream = null; Vector3f v3f = null; 

然后:

 serverSocket = new ServerSocket(port); 

最后:

 while (true) { socket = serverSocket.accept(); inStream = new ObjectInputStream(socket.getInputStream()); v3f = (Vector3f) inStream.readObject(); v3f.x += 10; v3f.y += 10; v3f.z += 10; outStream = new ObjectOutputStream(socket.getOutputStream()); outStream.writeObject(v3f); } 

哦,别忘了在Vector3f类中实现Serializable 🙂