所以我在这里,有一个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(显然)。
我只想知道如何将此对象发送到服务器(或主机),然后服务器将对象编辑为具有不同的值,然后将其发回。 E.g:
在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);
任何帮助都会很棒。请记住,这还没有进入我的游戏,所以现在只有这3个类,其中Client类有自己的main方法,Server类也是如此。
答案 0 :(得分:3)
事实证明,它很简单:
客户端:
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:)