Java-Gaming.org Hi !
Featured games (83)
games approved by the League of Dukes
Games in Showcase (511)
Games in Android Showcase (119)
games submitted by our members
Games in WIP (577)
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  
  Networking  (Read 1650 times)
0 Members and 1 Guest are viewing this topic.
Offline Zushii

Senior Newbie





« Posted 2011-05-24 16:38:53 »

Hello all together Cheesy

I'm currently trying to get a network game going.
I'm using Sockets and Objekt Serialization, because thats what we are doing in class and I need to use them later in exams.
After alot of working and trying out, I got the Server to send an Object and the Client to recieve it.

But for some miraculous reason, it will send the Object and recieve it, but will not update it.
So its something client sided. Because the server only recieves the old object.

So it will send the Player Object: with x 100 and y 100. Eventhough I updated it on the client side to eg x 140 and y 132

Oh and when your checking it, maybe someone could tell me why I get two connections when connecting to the server?

Thanks alot Cheesy

Heres the code:

Server:

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  
import java.io.*;
import java.net.*;

public class Server extends Thread {

   private ServerSocket arrayServer;
 

   public static void main(String argv[]) throws Exception {
     new Server();
   }

   public Server() throws Exception {
     arrayServer = new ServerSocket(9999);
     System.out.println("Server listening on port 4000.");
     this.start();
   }

   public void run() {
     while(true) {
       try {
        System.out.println("Waiting for connections.");
        Socket client = arrayServer.accept();
        System.out.println("Accepted a connection from: "+
client.getInetAddress());
        Connect c = new Connect(client);
       } catch(Exception e) {}
     }
   }
}

class Connect extends Thread {
   private Socket client = null;
   private ObjectInputStream ois = null;
   private ObjectOutputStream oos = null;
   
   public Connect() {}

   public Connect(Socket clientSocket) {
     client = clientSocket;
     try {
      ois = new ObjectInputStream(client.getInputStream());
      oos = new ObjectOutputStream(client.getOutputStream());
     } catch(Exception e1) {
         try {
            client.close();
         }catch(Exception e) {
           System.out.println(e.getMessage());
         }
         return;
     }
     this.start();
   }

   public void run() {
     
      while (true) {
     
      Object obj = null;
       
      try {
         obj = ois.readObject();
         System.out.println((Player)obj);
         
         if (obj instanceof Player) {
            oos.writeObject((Player)obj);
            //oos.flush();
         }
         
      } catch (IOException e) {
         // TODO Auto-generated catch block
         e.printStackTrace();
      } catch (ClassNotFoundException e) {
         // TODO Auto-generated catch block
         e.printStackTrace();
      }
       
       /*// close connections
         ois.close();
         oos.close();
         client.close(); */

      }    
   }
}


Client (with Slick2D):

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  
import java.awt.Point;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.OutputStream;
import java.net.Socket;
import java.util.ArrayList;

import org.newdawn.slick.Color;
import org.newdawn.slick.GameContainer;
import org.newdawn.slick.Graphics;
import org.newdawn.slick.Image;
import org.newdawn.slick.Input;
import org.newdawn.slick.SlickException;
import org.newdawn.slick.Sound;
import org.newdawn.slick.geom.Circle;
import org.newdawn.slick.geom.Rectangle;
import org.newdawn.slick.particles.ConfigurableEmitter;
import org.newdawn.slick.particles.ParticleEmitter;
import org.newdawn.slick.particles.ParticleIO;
import org.newdawn.slick.particles.ParticleSystem;
import org.newdawn.slick.particles.effects.FireEmitter;
import org.newdawn.slick.state.BasicGameState;
import org.newdawn.slick.state.StateBasedGame;
 
public class GameplayState extends BasicGameState {
 
    int stateID = -1;
 
    GameplayState( int stateID )
    {
       this.stateID = stateID;
    }
 
    @Override
    public int getID() {
        return stateID;
    }
 
    //Attribute
    GameClient client = null;
   
    Player me;
    ArrayList<Player> players = new ArrayList<Player>();
    String debugStr = "";

    public void init(GameContainer gc, StateBasedGame sbg) throws SlickException {
 
       // Objekt client erzeugen
        client = new GameClient();
        //client.starteClient("127.0.0.1", 9999);
       
        me = new Player(0,100,100);
        me.nick = "ad";
       
    }
 
    public void render(GameContainer gc, StateBasedGame sbg, Graphics g) throws SlickException {
       
       for (Player p: players) {
          g.drawRect(p.x, p.y, p.width, p.height);
       }
       
       g.drawString(debugStr, 10, 20);
    }
   
   
   
    public void update(GameContainer gc, StateBasedGame sbg, int delta) throws SlickException {
       
       //Handle Keyinputs Clientsided
       Input input = gc.getInput();
       
       if (input.isKeyDown(input.KEY_W)) {
          me.moveUp();
       }
       
       if (input.isKeyDown(input.KEY_S)) {
          me.moveDown();
       }
       
       if (input.isKeyDown(input.KEY_A)) {
          me.moveLeft();
       }
       
       if (input.isKeyDown(input.KEY_D)) {
          me.moveRight();
       }
       
       debugStr = me.toString();
       
       client.sendTCP(me);
    }
   
 
   
 // innere Klasse GameClient
    public class GameClient {
      private String       host;
      private int          port;
      private ReaderThread reader;
      private Socket       socket;
      ObjectOutputStream oos = null;
      ObjectInputStream ois = null;
     
      public GameClient(){
         starteClient("127.0.0.1",9999);
      }

      public boolean starteClient(String host, int port){
          try {
            socket = new Socket(host, port);
           
            // connect war erfolgreich
            this.host= host;
            this.port= port;
           
            oos = new ObjectOutputStream(socket.getOutputStream());
            ois = new ObjectInputStream(socket.getInputStream());
           
            // Lese Thread starten
            reader = new ReaderThread();
            reader.start();
            return true;
          }
          catch (IOException e){
            System.err.println(e);
            return false;
          }
         
         
      }

      public void sendTCP(Object o){
         try {
              oos.writeObject(o);
              //oos.flush();
          } catch (IOException ex) {
              //Logger.getLogger(JChatView.class.getName()).log(Level.SEVERE, null, ex);
          }

  }
     

        // innere Klasse um parallel eingehende Nachrichten zu lesen
          class ReaderThread extends Thread {
           public void run(){
               
               while (true) {
                 
                    try {
                  Player obj = (Player)ois.readObject();
                 
                     boolean b = false;
                     int i = 0;
                     
                     for (Player p: players) {
                       
                       
                        if (p == obj) {
                           b = true;
                           players.set(i, obj);
                           //System.out.println(obj);
                           //System.out.println("Recieved Player "+i+"["+players.size()+"]");
                        }
                       
                        i++;
                     }
                     
                     if (!b) {
                        players.add(obj);
                        System.out.println("Recieved New Player");
                     }
                     
                 
                 
                  //System.out.println("Recieved Player: "+obj.toString());
                 
               } catch (IOException e) {
                  // TODO Auto-generated catch block
                  e.printStackTrace();
               } catch (ClassNotFoundException e) {
                  // TODO Auto-generated catch block
                  e.printStackTrace();
               }
                   
                   
                   
               }
               
               
            }
          } // Ende innere Klasse ClientReader


      public void beendeClient() {
         try {
           oos.close();
           ois.close();
           socket.close();
         }
         catch (IOException e){
           System.err.println(e);
         }
      }
 
    }// innere Klasse Client
 
}


And the Player Class:

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  
import java.awt.Rectangle;
import java.io.Serializable;

public class Player implements Serializable {

   
   int id;
   String nick;

   float x,y;
   double aimAngle;

   int width = 50, height = 50;

   Rectangle r;

   public Player(int id, float x, float y) {
      this.id = id;
      this.x = x;
      this.y = y;
   }

   
   
   public int getId() {
      return id;
   }



   public void setId(int id) {
      this.id = id;
   }



   public String getNick() {
      return nick;
   }



   public void setNick(String nick) {
      this.nick = nick;
   }



   public float getX() {
      return x;
   }



   public void setX(float x) {
      this.x = x;
   }



   public float getY() {
      return y;
   }



   public void setY(float y) {
      this.y = y;
   }



   public double getAimAngle() {
      return aimAngle;
   }



   public void setAimAngle(double aimAngle) {
      this.aimAngle = aimAngle;
   }



   public int getWidth() {
      return width;
   }



   public void setWidth(int width) {
      this.width = width;
   }



   public int getHeight() {
      return height;
   }



   public void setHeight(int height) {
      this.height = height;
   }


   public void moveUp() {
      y -= 1;
   }
   
   public void moveDown() {
      y += 1;
   }

   public void moveLeft() {
      x -= 1;
   }
   
   public void moveRight() {
      x += 1;
   }
   
   public Rectangle getRect() {
      return new Rectangle((int)x,(int)y,width,height);
   }

   public String toString() {
      return this.nick +";"+ this.x +";"+ this.y +";"+ this.aimAngle +";"+ this.width +";"+ this.height +";"+ this.id;

   }
}

Offline zoto

Senior Duke


Medals: 4



« Reply #1 - Posted 2011-05-24 22:56:41 »

Client line 162 is
1  
 if (p == obj) {

it should be
1  
if( p.equals( obj ) ) {
Offline Zushii

Senior Newbie





« Reply #2 - Posted 2011-05-25 08:08:47 »

EDIT: Found the problem. I needed to oos.reset(); the OutputStream, so it would disregard the object if it has been sent.
Games published by our own members! Check 'em out!
Legends of Yore - The Casual Retro Roguelike
Offline ra4king

JGO Kernel


Medals: 350
Projects: 3
Exp: 5 years


I'm the King!


« Reply #3 - Posted 2011-05-25 12:59:49 »

Client line 162 is
1  
 if (p == obj) {

it should be
1  
if( p.equals( obj ) ) {

He doesn't have an "equals()" method in his Player class so that won't change anything.

@Zushii
Yes but you also need to change that line 162 to "if(obj instanceof Player) {"
Since all objects coming in will not be the same as existing ones.

Offline ra4king

JGO Kernel


Medals: 350
Projects: 3
Exp: 5 years


I'm the King!


« Reply #4 - Posted 2011-05-25 19:24:45 »

EDIT: Found the problem. I needed to oos.reset(); the OutputStream, so it would disregard the object if it has been sent.
Ah yes, I forgot to mention in my earlier post that ObjectOutputStream checks to see if that object has already been sent and only notifies the other side about it. It doesn't send a new copy. Instead of using "oos.reset()", you need to use "oos.writeUnshared(Object)" and "ois.readUnshared()".

Offline Zushii

Senior Newbie





« Reply #5 - Posted 2011-06-05 15:14:10 »

I've got a new Problem.

In my Player Class I have implemented a ArrayList<Missile>. Missile is a serializable Class and is just the missile.
I can add missiles client sided, but when I send the Player class containing the ArrayList with missiles the arraylist ist empty.

This is fairly weird. Since I can send ArrayList with no problem on its own. Is there a certain method I have to use here?
Offline ra4king

JGO Kernel


Medals: 350
Projects: 3
Exp: 5 years


I'm the King!


« Reply #6 - Posted 2011-06-06 02:30:22 »

Try using "writeUnshared" instead of "writeObject"

Offline Zushii

Senior Newbie





« Reply #7 - Posted 2011-06-06 11:57:08 »

I actually did that^^
The class shown in my first post is older.

Thats why I am confused.
Offline cylab

JGO Ninja


Medals: 52



« Reply #8 - Posted 2011-06-06 14:37:32 »

Post the current code... better a minimal self contained test case (usually you'll find the problem yourself in the process of creating a minimal selfcontained test case anyway Wink)

Mathias - I Know What [you] Did Last Summer!
Offline biro
« Reply #9 - Posted 2011-06-06 15:01:49 »

Hello,
I have a question about this:
I wouldn't send objects through the network, but only text, that stands for my missile.
As an example:
I would send:
m:11:move:11/22

m = missile
11 = ID of the missile
move = the command
11 = the new x-coordinate
22 = the new y-coordinate.

So why sending objects, when text should be a little bit faster?

if you want less text you could send byte messages... where you change move to a number and the symbols through a a few selected bytes...

biro
Games published by our own members! Check 'em out!
Legends of Yore - The Casual Retro Roguelike
Offline cylab

JGO Ninja


Medals: 52



« Reply #10 - Posted 2011-06-06 15:04:58 »

don't hijack topics, start your own!

EDIT: Sorry about that rant. Your post is absolutely fine - I should have read it to the end to realize, that you are proposing a simpler alternative...  Undecided

So why sending objects, when text should be a little bit faster?

if you want less text you could send byte messages... where you change move to a number and the symbols through a a few selected bytes...

You are absolutely right, defining an own simple text based network "protocol", would make things more deterministic, easier to debug and probably faster. On the downside, you can only send and receive data, your network code knows of.

Using serialization may have the advantage of being more abstract and you are getting the send and receive logic more or less for free.


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

JGO Kernel


Medals: 350
Projects: 3
Exp: 5 years


I'm the King!


« Reply #11 - Posted 2011-06-06 20:00:49 »

All that is fine, but we can't just abandon a bug that is supposed to work fine.
Zushii, could you show us some code?

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.

Longarmx (50 views)
2014-10-17 03:59:02

Norakomi (39 views)
2014-10-16 15:22:06

Norakomi (31 views)
2014-10-16 15:20:20

lcass (36 views)
2014-10-15 16:18:58

TehJavaDev (66 views)
2014-10-14 00:39:48

TehJavaDev (65 views)
2014-10-14 00:35:47

TehJavaDev (56 views)
2014-10-14 00:32:37

BurntPizza (72 views)
2014-10-11 23:24:42

BurntPizza (44 views)
2014-10-11 23:10:45

BurntPizza (84 views)
2014-10-11 22:30:10
Understanding relations between setOrigin, setScale and setPosition in libGdx
by mbabuskov
2014-10-09 22:35:00

Definite guide to supporting multiple device resolutions on Android (2014)
by mbabuskov
2014-10-02 22:36:02

List of Learning Resources
by Longor1996
2014-08-16 10:40:00

List of Learning Resources
by SilverTiger
2014-08-05 19:33:27

Resources for WIP games
by CogWheelz
2014-08-01 16:20:17

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

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

List of Learning Resources
by SilverTiger
2014-07-31 16:26:06
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!