New to Java Networking in Gaming

So once again I come to ask a question about making a game in Java, this time about networking. I’m trying to make a game with a lobby that allows you to either create a new server, or lets you join from a list of currently available servers similar to the system from Haxball, Stick Arena, etc. However, I really have no idea how to start or what key words I should be using to look this up so any help would be appreciated.

(also i wanted to see what this smiley looks like) :persecutioncomplex:

Start with KryoNet. Read the tutorial on the front page, it should get you started pretty quickly.

Thanks. With Kyronet, would one need to know the IP address of the server they wish to play on beforehand? Also, if I use the KyroNet library, people who play the game won’t need to download it, right?

yes.

They won’t need to download KryoNet separately, its a library and will be part of your game.

hmmm… do you know if there exist any libraries or methods in which the program could look up all available servers? if not i can do it like this, but being able to have some sort of lobby would be preferable

All available servers on the whole Internet? I’m sorry but that won’t work… It makes more sense that when someone starts a server in the lobby you register that and then other people can join that server with the ip address you provide.

Just a warning, if people will host their own servers and you don’t want them to talk to the servers through your server (and instead directly) the people who set up servers will have to open a port in their firewall/router.

Mike

Oh, I see, okay then thanks for the help I guess I’ll just use KyroNet because I really don’t think I could set up a dedicated server… Thanks.

You will have to!

A lobby in a game simply is a client to a dedicated server. The server has to provide some functionality to allow other servers of your game to register itself (and for the lobby to get the list of available games/servers).

So you need a central dedicated server that acts like a bulletin board where other compatible servers leave notes with their own IP-Address etc.

KyroNet is just a piece of code that makes it easier to write such stuff.

You can use DynDNS (a free service) to have a hostname point to your home IP address:
http://www.dyndns.com/services/dns/dyndns/
Eg, this would allow you to use “dcco.dnsalias.com” which would resolve to your home IP address. There are services available that will keep your DynDNS up to date if your IP address changes. This way you can use your home machine as a central server that keeps track of all other servers that are available. You could use KryoNet for this, or you could use something like PHP/MySQL.

KryoNet can find all servers running on the same LAN (see Client.discoverHost), but not the entire internet unless you use a central server as described above.

I see, thank you a lot guys.

What ended up happening so far is that I decided to take a stab at writing up some of my own code using the default java.net libraries since attempting to add the kryonet library was a little confusing for me and it’s going okay so far, however I have a new problem.

The TCP connection I have works fine however at the beginning of my program, however as the program continues to run, the input from the client takes longer and longer to transfer to the server. I am thinking that this is probably because TCP processes every packet that comes through and eventually at some point it can no longer catch up, so how would I fix this? Would simply sending the packets less often work? Is there some way I could have my socket decide not to receive redundant packets?

thanks in advance guys.

[quote]The TCP connection I have works fine however at the beginning of my program, however as the program continues to run, the input from the client takes longer and longer to transfer to the server. I am thinking that this is probably because TCP processes every packet that comes through and eventually at some point it can no longer catch up, so how would I fix this? Would simply sending the packets less often work? Is there some way I could have my socket decide not to receive redundant packets?
[/quote]
It might be best for you to post some self-contained code that demonstrates the problem. TCP by its nature regulates how fast it should be sending packets and it also takes care of resending packets in case ones were dropped. The implementation details of this should not be of any concern that your program needs to worry about.

since there isn’t really a lot going on in my code yet, ill post all of it

import java.awt.*;
import java.awt.event.*;
import java.awt.image.*;

import java.io.*;

import javax.imageio.*;
import javax.swing.*;

import java.net.*;

public class NetGades
{
	static int awid = 256, ahei = 256;
	static Server serv = null;
	static Client cli = null;

	static Rect p1, p2;
	
	static boolean clef = false, crig = false;
	
	static boolean isserv = true;
	
	public static void main (String[]args)
	{
		JFrame aa = new JFrame("Game");
	    aa.setSize(awid,ahei);
	    aa.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
	    aa.setContentPane(new GPanel());
	    KeyListener k = new KeyListener()
	    {
	    	public void keyPressed(KeyEvent e) 
	    	{
	    		int ckey = e.getKeyCode();
	    		if (ckey == KeyEvent.VK_LEFT) {clef = true;}
	    		if (ckey == KeyEvent.VK_RIGHT) {crig = true;}
	    		if (ckey == KeyEvent.VK_UP) {}
	    		if (ckey == KeyEvent.VK_DOWN) {}
	    		if (ckey == KeyEvent.VK_SPACE) {}
	    	}
	    	public void keyReleased(KeyEvent e) 
	    	{
	    		int ckey = e.getKeyCode();
	    		if (ckey == KeyEvent.VK_LEFT) {clef = false;}
	    		if (ckey == KeyEvent.VK_RIGHT) {crig = false;}
	    		if (ckey == KeyEvent.VK_UP) {}
	    		if (ckey == KeyEvent.VK_DOWN) {}
	    		if (ckey == KeyEvent.VK_SPACE) {}
	    	}
	    	public void keyTyped(KeyEvent e) {}
	    };
	    aa.addKeyListener(k);
	    
	   	MouseListener m = new MouseListener()
	    {
	    	public void mouseClicked(MouseEvent e){}
	    	public void mouseEntered(MouseEvent e){}
	    	public void mouseExited(MouseEvent e){}
	    	public void mousePressed(MouseEvent e)
	    	{
	    	}
	    	public void mouseReleased(MouseEvent e)
	    	{
	    	}
	    };
	    aa.addMouseListener(m);
	    
	    MouseMotionListener mm = new MouseMotionListener()
	    {    	
	    	public void mouseMoved(MouseEvent e)
	    	{
	    	}
	    	public void mouseDragged(MouseEvent e)
	    	{
	    	}
	    };
	    aa.addMouseMotionListener(mm);
	    
	    aa.pack();
	    aa.setVisible(true);
	}
	
	public static class GPanel extends JPanel
	{
		Timer tr;
		
		GPanel()
		{
			setPreferredSize(new Dimension(awid, ahei));
	        setBorder(BorderFactory.createLineBorder(Color.BLACK));

	        p1 = new Rect(80,80,16,16);
	        p2 = new Rect(160,80,16,16);
	        
	        if (isserv)
	        {
	        	serv = new Server(6999);
	        }
	        else
	        {
	        	cli = new Client("127.0.0.1",6999);
	        }
	        
	        tr = new Timer(10, new TimerAction());
	        tr.start();
		}
		
	    public void paintComponent(Graphics g) 
	    {
	    	g.setColor(Color.LIGHT_GRAY);
	    	g.fillRect(0,0,awid,ahei);
	    	
	    	p1.draw(g);
	    	p2.draw(g);
	    }
	    
	    public class TimerAction implements ActionListener
	    {
	        public void actionPerformed(ActionEvent e) 
	    	{
	        	if (clef) p2.x--;
	        	if (crig) p2.x++;
		        if (isserv)
		        {
		        	serv.tick();
		        }
		        else
		        {
		        	cli.tick();
		        }
	            repaint();
	        }
	    }
	}
	
	public static class Rect
	{
		double x, y;
		double wid, hei;
		
		Rect(double a, double b, double c, double d)
		{
			x = a; y = b;
			wid = c; hei = d;
		}
		
		boolean checkCL(Rect a, double l1, double l2)
		{
			return (l1-1 <= a.x+a.wid-1 && l1-1 >= a.x && (l2+hei-1) >= a.y && l2 <= a.y+a.hei-1);
		}
		boolean checkCR(Rect a, double l1, double l2)
		{
			return (l1+wid <= a.x+a.wid-1 && l1+wid >= a.x && (l2+hei-1) >= a.y && l2 <= a.y+a.hei-1);
		}
		boolean checkCT(Rect a, double l1, double l2)
		{
			return (l2-1 <= a.y+a.hei-1 && l2-1 >= a.y && (l1+wid-1) >= a.x && l1 <= a.x+a.wid-1);
		}
		boolean checkCB(Rect a, double l1, double l2)
		{
			return (l2+hei <= a.y+a.hei-1 && l2+hei >= a.y && (l1+wid-1) >= a.x && l1 <= a.x+a.wid-1);
		}
		boolean checkCBox(Rect a, double l1, double l2)
		{
			return (l2+hei-1 >= a.y && l2 <= a.y+a.hei-1 && l1+wid-1 >= a.x && l1 <= a.x+a.wid-1);
		}
		
		void tick(int i) {}
		void draw(Graphics g) 
		{
			g.setColor(Color.BLACK);
			g.fillRect((int)x,(int)y,(int)wid,(int)hei);
		}
	}
	
	public static class Server
	{
		private Socket          socket   = null;
		private ServerSocket    server   = null;
		private DataInputStream streamIn =  null;
		boolean foundClient = false;
		boolean done = false;
		
		public Server(int port)
		{  
			try
		    {  
				server = new ServerSocket(port);  
		    } 
			catch(IOException ioe) {}
		}
		
		void tick()
		{
			if (!done)
			{
				try
			    {  
					if (!foundClient)
					{
						socket = server.accept();
						foundClient = true;
						open();
					}
					else
			        {  
			        	try
			            {  
			        		String temp = streamIn.readUTF();
			        		p2.x = Double.parseDouble(temp);
			        		//done = true;
			            }
			            catch(IOException ioe)
			            {  
			            	//done = true;
			            }
			        }
			        
			   } catch(IOException ioe) {}
			}
			else
			{
				try 
				{
					close();
				} 
				catch (IOException e) {}
			}
		}
		
		void open() throws IOException
		{  
			streamIn = new DataInputStream(new BufferedInputStream(socket.getInputStream()));
		}
		
		void close() throws IOException
		{  
			if (socket != null)    socket.close();
		    if (streamIn != null)  streamIn.close();
		}
	}

	public static class Client
	{  
		private Socket socket              = null;
		private DataInputStream  console   = null;
		private DataOutputStream streamOut = null;

		boolean hasServer = false;
		
		String name = "";
		int port = 6999;
		
		public Client(String serverName, int serverPort)
		{  
			name = serverName;
			port = serverPort;
			connect();
		}
		
		public void connect()
		{
			try
		    {  
				socket = new Socket(name, port);
				hasServer = true;
		    	start();
		    }
		    catch(Exception e) {}
		}
		
		public void tick()
		{
			if (hasServer)
			{
			    send(p2);
			}
			else
			{
				connect();
			}
		}
		
		public void send(Rect r)
		{
		    try
		    {  
				String temp = "0.0";
		    	temp = ""+r.x;
		        streamOut.writeUTF(temp);
		        streamOut.flush();
		    }
		    catch(Exception e) {}
		}
		
		public void start() throws IOException
		{  
			console   = new DataInputStream(System.in);
		    streamOut = new DataOutputStream(socket.getOutputStream());
		}
		public void stop()
		{  
			try
		    {  
				if (console   != null)  console.close();
		        if (streamOut != null)  streamOut.close();
		        if (socket    != null)  socket.close();
		    }
		    catch(Exception e) {}
		}
	}
	
}

if you change isserv to true at the beginning it’ll run as the server program, if it’s changed to false it’ll be the client. what happens atm is the client program can use the arrow keys to move one of the boxes left and right, and the changes are supposed to be noticeable on the other’s screen

Hi, thanks for the code. I was able to reproduce the behavior on my system.

I noticed a couple of things:

  1. You’re sending a message every tick even though there may not be a need to.
  2. You write one string in the client and you only read one string in the sender each tick! Remember that tcp is a lossless protocol and if the client somehow gets ahead (e.g. java Timers don’t always fire exactly when you specify them) then the server is still only reading one string instead of all data available and thus the receiving queue may still have stuff in it. I.e. the latest position has already arrived at the server but your code only reads one string every tick. The issue is your sending and receiving buffers are getting out of sync within your application and has nothing to do with tcp/ip.

This is what I would do:

  1. On the server side keep reading until the buffer is empty. That should fix the lag over time.
  2. Restructure your networking so that the client only sends a message when it needs to e.g. the key-state changes.

Also keep in mind that by using a Timer on your server that fires every 50 ms you are throttling your server. A server should process messages as fast as it can rather than be artificially limited in some way.

It is standard on the server-side to have a thread that:
while (true) {
read message from socket
process message
}

I took your code and implemented essentially the same program using KryoNet:

import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.io.IOException;
import java.util.Random;
import java.util.concurrent.CopyOnWriteArrayList;

import javax.swing.BorderFactory;
import javax.swing.JFrame;
import javax.swing.JPanel;

import com.esotericsoftware.kryo.Kryo;
import com.esotericsoftware.kryonet.Client;
import com.esotericsoftware.kryonet.Connection;
import com.esotericsoftware.kryonet.Listener;
import com.esotericsoftware.kryonet.Server;
import com.esotericsoftware.minlog.Log;

public class NetGades {
	public static final int gameWidth = 256;
	public static final int gameHeight = 256;
	public static final int pixelsPerSecond = 40;

	public static class Network {
		public static int port = 55777;

		public static class Key {
			public boolean pressed;
			public int keyCode;
		}

		public static class Position {
			public int id;
			public float x, y;
		}

		public static class Remove {
			public int id;
		}

		public static void register (Kryo kryo) {
			kryo.register(Key.class);
			kryo.register(Position.class);
		}
	}

	public static class GameClient extends JPanel {
		private CopyOnWriteArrayList<Player> players = new CopyOnWriteArrayList();
		private Client client = new Client();

		GameClient () {
			setBorder(BorderFactory.createLineBorder(Color.BLACK));
			setBackground(Color.LIGHT_GRAY);
			setPreferredSize(new Dimension(gameWidth, gameHeight));

			setFocusable(true);
			addKeyListener(new KeyAdapter() {
				public void keyPressed (KeyEvent e) {
					sendKey(e.getKeyCode(), true);
				}

				public void keyReleased (KeyEvent e) {
					sendKey(e.getKeyCode(), false);
				}

				private void sendKey (int keyCode, boolean pressed) {
					if (!client.isConnected()) return;
					switch (keyCode) {
					case KeyEvent.VK_LEFT:
					case KeyEvent.VK_RIGHT:
						Network.Key key = new Network.Key();
						key.pressed = pressed;
						key.keyCode = keyCode;
						client.sendTCP(key);
					}
				}
			});

			client.addListener(new Listener() {
				public void received (Connection connection, Object object) {
					if (object instanceof Network.Position) {
						Network.Position position = (Network.Position)object;
						Player player = getPlayer(position.id);
						if (player == null) {
							player = new Player();
							player.id = position.id;
							players.add(player);
						}
						player.x = position.x;
						player.y = position.y;
						repaint();
					}

					if (object instanceof Network.Remove) {
						Network.Remove remove = (Network.Remove)object;
						Player player = getPlayer(remove.id);
						if (player != null) players.remove(player);
					}
				}

				public void disconnected (Connection connection) {
					System.exit(0);
				}
			});

			Network.register(client.getKryo());
			client.start();
		}

		private Player getPlayer (int id) {
			for (Player player : players)
				if (player.id == id) return player;
			return null;
		}

		public void paintComponent (Graphics g) {
			g.clearRect(0, 0, getWidth(), getHeight());
			for (Player player : players)
				player.draw(g);
		}

		public void connect () {
			try {
				client.connect(8000, "localhost", Network.port);
			} catch (IOException ex) {
				throw new RuntimeException(ex);
			}
		}

		public static void main (String[] args) {
			Log.DEBUG();

			final JFrame frame = new JFrame("Game");
			frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

			final GameClient gameClient = new GameClient();
			frame.setContentPane(gameClient);

			frame.pack();
			frame.setVisible(true);

			new Thread("Connect") {
				public void run () {
					try {
						gameClient.connect();
					} catch (Exception ex) {
						ex.printStackTrace();
						frame.dispose();
					}
				}
			}.start();
		}
	}

	public static class GameServer extends Server {
		private CopyOnWriteArrayList<Player> players = new CopyOnWriteArrayList();
		private Random random = new Random();

		public GameServer () throws IOException {
			addListener(new Listener() {
				public void connected (Connection connection) {
					int id = connection.getID();

					// Send new connection all the existing players.
					for (Player player : players)
						sendToTCP(id, getPosition(player));

					// Add new player.
					Player player = new Player();
					player.id = connection.getID();
					player.x = random.nextInt((int)(gameWidth - player.width));
					player.y = random.nextInt((int)(gameHeight - player.height));
					players.add(player);

					// Send new player to everyone.
					sendToAllTCP(getPosition(player));
				}

				public void disconnected (Connection connection) {
					players.remove(getPlayer(connection.getID()));

					Network.Remove remove = new Network.Remove();
					remove.id = connection.getID();
					sendToAllTCP(remove);
				}

				public void received (Connection connection, Object object) {
					Player player = getPlayer(connection.getID());
					if (player == null) return;
					if (object instanceof Network.Key) {
						Network.Key key = (Network.Key)object;
						switch (key.keyCode) {
						case KeyEvent.VK_LEFT:
							player.movingLeft = key.pressed;
							break;
						case KeyEvent.VK_RIGHT:
							player.movingRight = key.pressed;
							break;
						}
					}
				}
			});
			Network.register(getKryo());
			bind(Network.port);
			start();

			new Thread() {
				public void run () {
					while (true) {
						tick(48);
						try {
							Thread.sleep(48);
						} catch (InterruptedException ignored) {
						}
					}
				}
			}.start();
		}

		Network.Position getPosition (Player player) {
			Network.Position position = new Network.Position();
			position.id = player.id;
			position.x = player.x;
			position.y = player.y;
			return position;
		}

		private Player getPlayer (int id) {
			for (Player player : players)
				if (player.id == id) return player;
			return null;
		}

		void tick (int delta) {
			for (Player player : players) {
				boolean moved = false;
				if (player.movingLeft) {
					player.x -= pixelsPerSecond * delta / 1000f;
					if (player.x < 0) {
						player.x = 0;
						player.movingLeft = false;
					}
					moved = true;
				}
				if (player.movingRight) {
					player.x += pixelsPerSecond * delta / 1000f;
					if (player.x > gameWidth - player.width) {
						player.x = gameWidth - player.width;
						player.movingRight = false;
					}
					moved = true;
				}
				if (moved) sendToAllTCP(getPosition(player));
			}
		}

		public static void main (String[] args) throws IOException {
			Log.DEBUG();
			new GameServer();
		}
	}

	public static class Player {
		int id;
		float x, y;
		float width = 16, height = 16;
		boolean movingLeft, movingRight;

		boolean checkCL (Player a, float l1, float l2) {
			return (l1 - 1 <= a.x + width - 1 && l1 - 1 >= a.x && (l2 + height - 1) >= a.y && l2 <= a.y + height - 1);
		}

		boolean checkCR (Player a, float l1, float l2) {
			return (l1 + width <= a.x + width - 1 && l1 + width >= a.x && (l2 + height - 1) >= a.y && l2 <= a.y + height - 1);
		}

		boolean checkCT (Player a, float l1, float l2) {
			return (l2 - 1 <= a.y + height - 1 && l2 - 1 >= a.y && (l1 + width - 1) >= a.x && l1 <= a.x + width - 1);
		}

		boolean checkCB (Player a, float l1, float l2) {
			return (l2 + height <= a.y + height - 1 && l2 + height >= a.y && (l1 + width - 1) >= a.x && l1 <= a.x + width - 1);
		}

		boolean checkCBox (Player a, float l1, float l2) {
			return (l2 + height - 1 >= a.y && l2 <= a.y + height - 1 && l1 + width - 1 >= a.x && l1 <= a.x + width - 1);
		}

		void draw (Graphics g) {
			g.setColor(Color.BLACK);
			g.fillRect((int)x, (int)y, (int)width, (int)height);
		}
	}
}

To compile, get the KryoNet JARs and add them to your classpath. To run, first run NetGades.GameServer, then run NetGades.GameClient. Note that you can run NetGades.GameClient multiple times, which will connect multiple players to the same server. When a player moves, it will move on all clients.

They way it works is this:

  • When a client connects, the server adds a new player and sends it to all clients.
  • Each client display the players the server has told them about.
  • When a key is pressed or released, the client tells the server about it. The server notes the direction that player is moving or not moving.
  • The server has a thread that checks each player every 48 milliseconds. If a player is moving, it updates the player’s position and sends the new position to all the clients.

This approach is secure, because the positions always come from the server. If the client told the server where the player is, that information would have to be validated, eg to prevent clients from cheating by teleporting around. However, until your game becomes very popular, I wouldn’t bother worrying too much about making it secure. Better to focus on making it fun!

A drawback to the above approach is that a player will continue to move until the server receives the “key released” message. If you run KryoNet from SVN, there is a Listener.LagListener class that can simulate lag to make the problem more obvious. For an action game with “twitch” controls, this latency may be undesirable. A more complex solution may be warranted.