OK, here goes…
I’m trying to build the simplest of simple networking things: a server that communicates with clients to move around 2 players who are in the same room. Unfortunately, after 2 messages are sent, the server and client somehow automatically disconnect. I’m not sure why. I can’t tell if the problem is on the server end, or the client end, or both. I’m using the physics tutorial as a base.
I’m not using spidermonkey, just sockets and stuff. I could not find a simple spidermonkey tutorial, and would honestly rather stick to what I know.
here’s the server code:
[java]package mygame;
import com.jme3.app.SimpleApplication;
import com.jme3.asset.plugins.ZipLocator;
import com.jme3.bullet.BulletAppState;
import com.jme3.bullet.collision.shapes.CapsuleCollisionShape;
import com.jme3.bullet.collision.shapes.CollisionShape;
import com.jme3.bullet.control.CharacterControl;
import com.jme3.bullet.control.RigidBodyControl;
import com.jme3.bullet.util.CollisionShapeFactory;
import com.jme3.input.KeyInput;
import com.jme3.input.controls.ActionListener;
import com.jme3.input.controls.KeyTrigger;
import com.jme3.light.AmbientLight;
import com.jme3.light.DirectionalLight;
import com.jme3.material.Material;
import com.jme3.math.ColorRGBA;
import com.jme3.math.Vector2f;
import com.jme3.math.Vector3f;
import com.jme3.scene.Geometry;
import com.jme3.scene.Node;
import com.jme3.scene.Spatial;
import com.jme3.scene.shape.Box;
import java.awt.event.ActionEvent;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;
/**
- Example 9 - How to make walls and floors solid.
- This collision code uses Physics and a custom Action Listener.
-
@author normen, with edits by Zathras
*/
public class Main extends SimpleApplication
implements ActionListener
{
private Spatial sceneModel;
private BulletAppState bulletAppState;
private RigidBodyControl landscape;
private CharacterControl player;
private Vector3f walkDirection = new Vector3f();
private boolean left = false, right = false, up = false, down = false;
//Temporary vectors used on each frame.
//They here to avoid instanciating new vectors on each frame
private Vector3f camDir = new Vector3f();
private Vector3f camLeft = new Vector3f();
//client/server stuff
BufferedReader in;
PrintWriter out;
//server stats
String roomID = “F1Hall”;
String playername = “”;
public static void main(String[] args)
{
Main app = new Main();
app.start();
}
public void simpleInitApp()
{
System.out.println(“renenbo”);
try
{
//get the name of the player
playername = JOptionPane.showInputDialog(“Player Name:”);
// Make connection and initialize streams
Socket socket = new Socket(JOptionPane.showInputDialog(“IP adress:”), 9001);
in = new BufferedReader(new InputStreamReader( socket.getInputStream()));
out = new PrintWriter(socket.getOutputStream(), true);
out.println("NEW_PLAYER " + roomID + " " + playername);
}
catch(Exception e)
{
System.out.println(e);
}
/** Set up Physics */
bulletAppState = new BulletAppState();
stateManager.attach(bulletAppState);
//bulletAppState.getPhysicsSpace().enableDebug(assetManager);
// We re-use the flyby camera for rotation, while positioning is handled by physics
viewPort.setBackgroundColor(new ColorRGBA(0.7f, 0.8f, 1f, 1f));
flyCam.setMoveSpeed(100);
setUpKeys();
setUpLight();
// We load the scene from the zip file and adjust its size.
assetManager.registerLocator("town.zip", ZipLocator.class);
sceneModel = assetManager.loadModel("main.scene");
sceneModel.setLocalScale(2f);
// We set up collision detection for the scene by creating a
// compound collision shape and a static RigidBodyControl with mass zero.
CollisionShape sceneShape =
CollisionShapeFactory.createMeshShape((Node) sceneModel);
landscape = new RigidBodyControl(sceneShape, 0);
sceneModel.addControl(landscape);
// We set up collision detection for the player by creating
// a capsule collision shape and a CharacterControl.
// The CharacterControl offers extra settings for
// size, stepheight, jumping, falling, and gravity.
// We also put the player in its starting position.
CapsuleCollisionShape capsuleShape = new CapsuleCollisionShape(1.5f, 6f, 1);
player = new CharacterControl(capsuleShape, 0.05f);
player.setJumpSpeed(20);
player.setFallSpeed(30);
player.setGravity(30);
player.setPhysicsLocation(new Vector3f(0, 10, 0));
// We attach the scene and the player to the rootnode and the physics space,
// to make them appear in the game world.
rootNode.attachChild(sceneModel);
bulletAppState.getPhysicsSpace().add(landscape);
bulletAppState.getPhysicsSpace().add(player);
}
private void setUpLight()
{
// We add light so we see the scene
AmbientLight al = new AmbientLight();
al.setColor(ColorRGBA.White.mult(1.3f));
rootNode.addLight(al);
DirectionalLight dl = new DirectionalLight();
dl.setColor(ColorRGBA.White);
dl.setDirection(new Vector3f(2.8f, -2.8f, -2.8f).normalizeLocal());
rootNode.addLight(dl);
}
/** We over-write some navigational key mappings here, so we can
- add physics-controlled walking and jumping: */
private void setUpKeys()
{
inputManager.addMapping(“Left”, new KeyTrigger(KeyInput.KEY_A));
inputManager.addMapping(“Right”, new KeyTrigger(KeyInput.KEY_D));
inputManager.addMapping(“Up”, new KeyTrigger(KeyInput.KEY_W));
inputManager.addMapping(“Down”, new KeyTrigger(KeyInput.KEY_S));
inputManager.addMapping(“Jump”, new KeyTrigger(KeyInput.KEY_SPACE));
inputManager.addListener(this, “Left”);
inputManager.addListener(this, “Right”);
inputManager.addListener(this, “Up”);
inputManager.addListener(this, “Down”);
inputManager.addListener(this, “Jump”);
}
/** These are our custom actions triggered by key presses.
- We do not walk yet, we just keep track of the direction the user pressed. */
public void onAction(String binding, boolean isPressed, float tpf)
{
if (binding.equals(“Left”)) {
left = isPressed;
} else if (binding.equals(“Right”)) {
right= isPressed;
} else if (binding.equals(“Up”)) {
up = isPressed;
} else if (binding.equals(“Down”)) {
down = isPressed;
} else if (binding.equals(“Jump”)) {
if (isPressed) { player.jump(); }
}
}
/**
- This is the main event loop–walking happens here.
- We check in which direction the player is walking by interpreting
- the camera direction forward (camDir) and to the side (camLeft).
- The setWalkDirection() command is what lets a physics-controlled player walk.
- We also make sure here that the camera moves with player.
*/
//set up an accumulator
int accumulator = 0;
@Override
public void simpleUpdate(float tpf)
{
accumulator++;
if(accumulator >= 3000)//
{
accumulator = 0;
try
{
out.println("MOVE_PLAYER " + roomID + " " + playername + " " + player.getPhysicsLocation());
System.out.println(out);
}
catch(Exception e)
{
System.out.println(e);
}
}
try
{
if(in.ready())
{
String line = in.readLine();
if(line != null && !line.equals(""))
{
System.out.println(line);
}
}
}
catch(Exception e)
{
}
camDir.set(cam.getDirection()).multLocal(0.6f);
camLeft.set(cam.getLeft()).multLocal(0.4f);
walkDirection.set(0, 0, 0);
if (left) {
walkDirection.addLocal(camLeft);
}
if (right) {
walkDirection.addLocal(camLeft.negate());
}
if (up) {
walkDirection.addLocal(camDir);
}
if (down) {
walkDirection.addLocal(camDir.negate());
}
player.setWalkDirection(walkDirection);
cam.setLocation(player.getPhysicsLocation());
}
}[/java]
and the client code:
[java]import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.lang.reflect.Array;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashSet;
import java.util.Scanner;
import java.util.StringTokenizer;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;
public class Server
{
//create an array of printWriters
//private static ArrayList<PrintWriter> writers = new ArrayList<PrintWriter>();
private static ArrayList<Handler> handlers = new ArrayList<Handler>();
//shared stuff
//GUI
JFrame frame = new JFrame("ADMIN_ACCESS");
JTextField textField = new JTextField(40);
JTextArea messageArea = new JTextArea(8, 40);
public static void main(String[] args) throws IOException
{
//create a server socket
ServerSocket listener = new ServerSocket(9001);
Server ADMIN_ACCESS = new Server();
try
{
while (true)
{
try
{
//creates a new handler and sets it to an accepted socket
new Handler(listener.accept()).start();
}
finally
{
listener.close();
}
}
}
catch(Exception e)
{
System.out.println("error, " + e);
}
finally
{
listener.close();
}
}
//constructor
public Server()
{
//Gooey constructor
//textField.setEditable(false);
//messageArea.setEditable(false);
frame.getContentPane().add(textField, "North");
frame.getContentPane().add(new JScrollPane(messageArea), "Center");
frame.pack();
frame.setAlwaysOnTop(true);
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
// Add Listener
textField.addActionListener(new ActionListener()
{
//OK, still don't get this piece.
public void actionPerformed(ActionEvent e)
{
//out.println(textField.getText());
for (int a = 0; a < handlers.size(); a++)//for ALL the handlers,...
{
handlers.get(a).printInstructions("input");//...distribute the input
}
textField.setText("");
}
});
}
private static class Handler extends Thread
{
private String name;
private Socket socket;
private BufferedReader in;
private PrintWriter out;
private String currentRoom = "";
private String playername = "";
private double x = 0;
private double y = 0;
private double z = 0;
//creates a socket for each object
public Handler(Socket socket)
{
this.socket = socket;
handlers.add(this);
run();
}
public void run()
{
try
{
StringTokenizer analasys;
int accumulator = 0;
in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
out = new PrintWriter(socket.getOutputStream(), true);
//writers.add(out);
while (true)
{
if(in.ready())
{
String input = in.readLine();
//System.out.println(input);
System.out.println(input);
if (input != null)
{
//for the chat
if(input.startsWith("MESSAGE:"))
{
for (int a = 0; a < handlers.size(); a++)//for ALL the handlers,...
{
handlers.get(a).printInstructions(input);//...distribute the input
}
}
if(input.startsWith("MOVE_PLAYER"))
{
analasys = new StringTokenizer(input);//tokenize
analasys.nextToken();//skip identifier
currentRoom = analasys.nextToken();//get room number
analasys.nextToken();//skip player name
x = Double.parseDouble(analasys.nextToken().substring(1));//get the x value
System.out.println(x);
//"MOVE_PLAYER " + roomID + " " + playername + " " + player.getPhysicsLocation());
for(int a = 0; a < handlers.size(); a++)//for all the handlers...
{
if(handlers.get(a).getCurrentRoom().equals(currentRoom))//...in the same room,...
{
handlers.get(a).printInstructions(input);//...redistribute the message
}
}
}
}
}
}
}
catch(Exception e)
{
}
finally
{
handlers.remove(this);
try
{
this.socket.close();
}
catch (IOException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
public String getCurrentRoom()
{
return currentRoom;
}
public void printInstructions(String message)
{
out.println(message);
System.out.println(message);
}
}
}
[/java]
I very much appreciate any help.