Java-Gaming.org    
Featured games (79)
games approved by the League of Dukes
Games in Showcase (477)
Games in Android Showcase (109)
games submitted by our members
Games in WIP (536)
games currently in development
News: Read the Java Gaming Resources, or peek at the official Java tutorials
 
    Home     Help   Search   Login   Register   
Pages: [1]
  ignore  |  Print  
  New to Java Networking in Gaming  (Read 8281 times)
0 Members and 1 Guest are viewing this topic.
Offline dcco

Senior Newbie





« Posted 2011-01-21 16:55:38 »

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
Online kappa
« League of Dukes »

JGO Kernel


Medals: 75
Projects: 15


★★★★★


« Reply #1 - Posted 2011-01-21 17:02:48 »

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

Senior Newbie





« Reply #2 - Posted 2011-01-21 17:14:14 »

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?
Games published by our own members! Check 'em out!
Legends of Yore - The Casual Retro Roguelike
Online kappa
« League of Dukes »

JGO Kernel


Medals: 75
Projects: 15


★★★★★


« Reply #3 - Posted 2011-01-21 17:16:02 »

With Kyronet, would one need to know the IP address of the server they wish to play on beforehand?
yes.

Also, if I use the KyroNet library, people who play the game won't need to download it, right?
They won't need to download KryoNet separately, its a library and will be part of your game.
Offline dcco

Senior Newbie





« Reply #4 - Posted 2011-01-21 17:21:59 »

With Kyronet, would one need to know the IP address of the server they wish to play on beforehand?
yes.
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
Offline Mike

JGO Ninja


Medals: 71
Projects: 1
Exp: 5 years


Java guru wanabee


« Reply #5 - Posted 2011-01-21 17:27:22 »

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

My current game, Minecraft meets Farmville and goes online Smiley
State of Fortune | Discussion thread @ JGO
Offline dcco

Senior Newbie





« Reply #6 - Posted 2011-01-21 17:29:48 »

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.
Offline cylab

JGO Ninja


Medals: 38



« Reply #7 - Posted 2011-01-21 18:02:59 »

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.

Mathias - I Know What [you] Did Last Summer!
Offline Nate

JGO Kernel


Medals: 145
Projects: 4
Exp: 14 years


Esoteric Software


« Reply #8 - Posted 2011-01-21 22:46:37 »

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.

Offline dcco

Senior Newbie





« Reply #9 - Posted 2011-01-23 06:24:53 »

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.
Games published by our own members! Check 'em out!
Legends of Yore - The Casual Retro Roguelike
Offline loom_weaver

JGO Coder


Medals: 17



« Reply #10 - Posted 2011-01-23 07:47:11 »

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?

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.
Offline dcco

Senior Newbie





« Reply #11 - Posted 2011-01-23 16:50:56 »

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

1  
2  
3  
4  
5  
6  
7  
8  
9  
10  
11  
12  
13  
14  
15  
16  
17  
18  
19  
20  
21  
22  
23  
24  
25  
26  
27  
28  
29  
30  
31  
32  
33  
34  
35  
36  
37  
38  
39  
40  
41  
42  
43  
44  
45  
46  
47  
48  
49  
50  
51  
52  
53  
54  
55  
56  
57  
58  
59  
60  
61  
62  
63  
64  
65  
66  
67  
68  
69  
70  
71  
72  
73  
74  
75  
76  
77  
78  
79  
80  
81  
82  
83  
84  
85  
86  
87  
88  
89  
90  
91  
92  
93  
94  
95  
96  
97  
98  
99  
100  
101  
102  
103  
104  
105  
106  
107  
108  
109  
110  
111  
112  
113  
114  
115  
116  
117  
118  
119  
120  
121  
122  
123  
124  
125  
126  
127  
128  
129  
130  
131  
132  
133  
134  
135  
136  
137  
138  
139  
140  
141  
142  
143  
144  
145  
146  
147  
148  
149  
150  
151  
152  
153  
154  
155  
156  
157  
158  
159  
160  
161  
162  
163  
164  
165  
166  
167  
168  
169  
170  
171  
172  
173  
174  
175  
176  
177  
178  
179  
180  
181  
182  
183  
184  
185  
186  
187  
188  
189  
190  
191  
192  
193  
194  
195  
196  
197  
198  
199  
200  
201  
202  
203  
204  
205  
206  
207  
208  
209  
210  
211  
212  
213  
214  
215  
216  
217  
218  
219  
220  
221  
222  
223  
224  
225  
226  
227  
228  
229  
230  
231  
232  
233  
234  
235  
236  
237  
238  
239  
240  
241  
242  
243  
244  
245  
246  
247  
248  
249  
250  
251  
252  
253  
254  
255  
256  
257  
258  
259  
260  
261  
262  
263  
264  
265  
266  
267  
268  
269  
270  
271  
272  
273  
274  
275  
276  
277  
278  
279  
280  
281  
282  
283  
284  
285  
286  
287  
288  
289  
290  
291  
292  
293  
294  
295  
296  
297  
298  
299  
300  
301  
302  
303  
304  
305  
306  
307  
308  
309  
310  
311  
312  
313  
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
Offline loom_weaver

JGO Coder


Medals: 17



« Reply #12 - Posted 2011-01-23 23:14:11 »

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.
Offline loom_weaver

JGO Coder


Medals: 17



« Reply #13 - Posted 2011-01-24 04:43:41 »

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
}
Offline Nate

JGO Kernel


Medals: 145
Projects: 4
Exp: 14 years


Esoteric Software


« Reply #14 - Posted 2011-01-24 23:03:28 »

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

1  
2  
3  
4  
5  
6  
7  
8  
9  
10  
11  
12  
13  
14  
15  
16  
17  
18  
19  
20  
21  
22  
23  
24  
25  
26  
27  
28  
29  
30  
31  
32  
33  
34  
35  
36  
37  
38  
39  
40  
41  
42  
43  
44  
45  
46  
47  
48  
49  
50  
51  
52  
53  
54  
55  
56  
57  
58  
59  
60  
61  
62  
63  
64  
65  
66  
67  
68  
69  
70  
71  
72  
73  
74  
75  
76  
77  
78  
79  
80  
81  
82  
83  
84  
85  
86  
87  
88  
89  
90  
91  
92  
93  
94  
95  
96  
97  
98  
99  
100  
101  
102  
103  
104  
105  
106  
107  
108  
109  
110  
111  
112  
113  
114  
115  
116  
117  
118  
119  
120  
121  
122  
123  
124  
125  
126  
127  
128  
129  
130  
131  
132  
133  
134  
135  
136  
137  
138  
139  
140  
141  
142  
143  
144  
145  
146  
147  
148  
149  
150  
151  
152  
153  
154  
155  
156  
157  
158  
159  
160  
161  
162  
163  
164  
165  
166  
167  
168  
169  
170  
171  
172  
173  
174  
175  
176  
177  
178  
179  
180  
181  
182  
183  
184  
185  
186  
187  
188  
189  
190  
191  
192  
193  
194  
195  
196  
197  
198  
199  
200  
201  
202  
203  
204  
205  
206  
207  
208  
209  
210  
211  
212  
213  
214  
215  
216  
217  
218  
219  
220  
221  
222  
223  
224  
225  
226  
227  
228  
229  
230  
231  
232  
233  
234  
235  
236  
237  
238  
239  
240  
241  
242  
243  
244  
245  
246  
247  
248  
249  
250  
251  
252  
253  
254  
255  
256  
257  
258  
259  
260  
261  
262  
263  
264  
265  
266  
267  
268  
269  
270  
271  
272  
273  
274  
275  
276  
277  
278  
279  
280  
281  
282  
283  
284  
285  
286  
287  
288  
289  
290  
291  
292  
293  
294  
295  
296  
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.

Pages: [1]
  ignore  |  Print  
 
 
You cannot reply to this message, because it is very, very old.

 

Add your game by posting it in the WIP section,
or publish it in Showcase.

The first screenshot will be displayed as a thumbnail.

CogWheelz (11 views)
2014-08-01 22:53:16

CogWheelz (13 views)
2014-08-01 22:51:43

CopyableCougar4 (15 views)
2014-08-01 19:37:19

CogWheelz (19 views)
2014-07-30 21:08:39

Riven (27 views)
2014-07-29 18:09:19

Riven (16 views)
2014-07-29 18:08:52

Dwinin (14 views)
2014-07-29 10:59:34

E.R. Fleming (35 views)
2014-07-29 03:07:13

E.R. Fleming (13 views)
2014-07-29 03:06:25

pw (44 views)
2014-07-24 01:59:36
Resources for WIP games
by CogWheelz
2014-08-01 18:20:17

Resources for WIP games
by CogWheelz
2014-08-01 18:19:50

List of Learning Resources
by SilverTiger
2014-07-31 18:29:50

List of Learning Resources
by SilverTiger
2014-07-31 18:26:06

List of Learning Resources
by SilverTiger
2014-07-31 13:54:12

HotSpot Options
by dleskov
2014-07-08 03:59:08

Java and Game Development Tutorials
by SwordsMiner
2014-06-14 00:58:24

Java and Game Development Tutorials
by SwordsMiner
2014-06-14 00:47:22
java-gaming.org is not responsible for the content posted by its members, including references to external websites, and other references that may or may not have a relation with our primarily gaming and game production oriented community. inquiries and complaints can be sent via email to the info‑account of the company managing the website of java‑gaming.org
Powered by MySQL Powered by PHP Powered by SMF 1.1.18 | SMF © 2013, Simple Machines | Managed by Enhanced Four Valid XHTML 1.0! Valid CSS!