Index: trunk/src/lib/network/Makefile.am
===================================================================
--- trunk/src/lib/network/Makefile.am	(revision 5997)
+++ trunk/src/lib/network/Makefile.am	(revision 6139)
@@ -11,5 +11,9 @@
                       data_stream.cc \
                       network_protocol.cc \
-		      server_socket.cc
+		      server_socket.cc \
+		      handshake.cc \
+		      network_game_manager.cc \
+		      converter.cc
+
 
 
@@ -22,4 +26,8 @@
                  data_stream.h \
                  network_protocol.h \
-		 server_socket.h
+		 server_socket.h \
+		 handshake.h \
+		 network_game_manager.h \
+		 converter.h
 
+
Index: trunk/src/lib/network/converter.cc
===================================================================
--- trunk/src/lib/network/converter.cc	(revision 6139)
+++ trunk/src/lib/network/converter.cc	(revision 6139)
@@ -0,0 +1,214 @@
+/*
+   orxonox - the future of 3D-vertical-scrollers
+
+   Copyright (C) 2004 orx
+
+   This program is free software; you can redistribute it and/or modify
+   it under the terms of the GNU General Public License as published by
+   the Free Software Foundation; either version 2, or (at your option)
+   any later version.
+
+### File Specific:
+   main-programmer: Benjamin Wuest
+   co-programmer: ...
+*/
+
+
+/* this is for debug output. It just says, that all calls to PRINT() belong to the DEBUG_MODULE_NETWORK module
+   For more information refere to https://www.orxonox.net/cgi-bin/trac.cgi/wiki/DebugOutput
+*/
+#define DEBUG_MODULE_NETWORK
+
+/* include your own header */
+#include "converter.h"
+
+
+/* using namespace std is default, this needs to be here */
+using namespace std;
+
+/*!
+ * Standard constructor
+ */
+Converter::Converter()
+{
+  /* set the class id for the base object */
+  //this->setClassID(CL_ENTITY_MANAGER, "EntityManager");
+}
+
+/*!
+ * Standard destructor
+ */
+Converter::~Converter()
+{
+}
+
+const int sgnadd = 128; // = 2^7
+
+/*!
+ * Converts an int into a byte-array
+ * @remarks: The int is stored in big-endian
+ * @param x: The int which is to convert
+ * @return: A byte-array that accords the given int value
+ */
+byte* Converter::intToByteArray(int x)
+{
+  const int mod = 256; // = 2^8
+  
+  
+  byte* result = new byte[INTSIZE];
+  int sgn;
+  if (x >= 0)
+    sgn = 1;
+  else
+  {
+    sgn = -1;
+    x = -x;
+  }
+  
+  for (int i = 0; i < INTSIZE; i++)
+  {
+    result[i] = x % mod;
+    x /= mod;
+  }
+  
+  if (sgn == -1)
+    result[INTSIZE - 1] += sgnadd;
+  
+  
+  return result;
+}
+
+/*!
+ * Converts a byte-array into an int
+ * @param a: The byte-array which is to convert
+ * @return: An int that accords the given byte-array
+ */
+int Converter::byteArrayToInt(byte* a)
+{
+  int mult = 1;
+  const int step = 256; // = 2 ^ 8
+  int result = 0;
+  for (int i = 0; i < INTSIZE - 1; i++)
+  {
+    result += a[i] * mult;
+    mult *= step;
+  }
+  
+  printf("tara: %i", result);
+  
+  if (a[INTSIZE - 1] >= sgnadd)
+  {
+    result += (a[INTSIZE - 1] - sgnadd) * mult;
+    result *= -1;
+  }
+  else
+    result += a[INTSIZE - 1] * mult;
+  
+  return result;
+}
+
+/*char* Converter::floatToBinString(float x)
+{
+  char* result = new char[200];
+  int pos = 0;
+  
+  int h = (int)x;
+  if (h > x)
+    h--;
+  x -= h;
+  
+  
+  while (h > 0 && pos < 200)
+  {
+    //printf("%i ", pos);
+    
+    if (h % 2 == 1)
+    {
+      result[pos] = '1';
+      h -= 1;
+    }
+    else
+      result[pos] = '0';
+    pos++;
+    h /= 2;
+  }
+  
+  //printf("x = %f\n", x);
+  
+  
+  //invert
+  for (int i = 0; i < pos / 2; i++)
+  {
+    char temp = result[i];
+    result[i] = result[pos - 1 - i];
+    result[pos - 1 - i] = temp;
+  }
+  
+  
+  result[pos++] = '.';
+  float sub = 0.5;
+  while (x > 0 && pos < 200)
+  {
+    //printf("%i ", pos);
+    
+    if (x >= sub)
+    {
+      result[pos] = '1';
+      x -= sub;
+    }
+    else
+      result[pos] = '0';
+    pos++;
+    sub /= 2;
+  }
+  
+  
+  return result;
+}*/
+
+char* Converter::floatToBinString(float x)
+{
+  char* result = new char[200];
+  int pos = 0;
+  
+  float sub = 1;
+  while (sub < x)
+    sub *= 2;
+  
+  //printf("sub = %f\n", sub);
+  
+  //while (sub >= 1 && pos < 200)
+  while ((x > 0 || sub >= 1) && pos < 200)
+  {
+    if (x >= sub)
+    {
+      result[pos] = '1';
+      x -= sub;
+    }
+    else
+      result[pos] = '0';
+    pos++;
+    sub /= 2;
+    
+    if (sub == 0.5f)
+      result[pos++] = '.';
+  }
+  
+  /*result[pos++] = '.';
+  sub = 0.5;
+  while (x > 0 && pos < 200)
+  {
+    if (x >= sub)
+    {
+      result[pos] = '1';
+      x -= sub;
+    }
+    else
+      result[pos] = '0';
+    pos++;
+    sub /= 2;
+  }
+  */
+  
+  return result;
+}
Index: trunk/src/lib/network/converter.h
===================================================================
--- trunk/src/lib/network/converter.h	(revision 6139)
+++ trunk/src/lib/network/converter.h	(revision 6139)
@@ -0,0 +1,38 @@
+/*!
+ * @file converter.h
+ *  Is able to convert int to byte-array and vice versa
+ */
+ 
+#ifndef _CONVERTER
+#define _CONVERTER
+
+/* include this file, it contains some default definitions */
+#include "netdefs.h"
+
+/* include base_object.h since all classes are derived from this one */
+#include "base_object.h"
+
+/* The size of an int in byte */
+#define INTSIZE 4
+
+/*!
+ * a class that can convert int to byte-array and vice versa
+ */
+class Converter: public BaseObject
+{
+  public:
+    static byte* intToByteArray(int x);
+    static int byteArrayToInt(byte* a);
+    
+    //byte* floatToByteArray(float x);
+    //float byteArrayToFloat(byte[] a);
+    
+    //Test
+    static char* floatToBinString(float x);
+    
+  private:
+    Converter();
+    ~Converter();
+};
+
+#endif /*_CONVERTER*/
Index: trunk/src/lib/network/handshake.cc
===================================================================
--- trunk/src/lib/network/handshake.cc	(revision 6139)
+++ trunk/src/lib/network/handshake.cc	(revision 6139)
@@ -0,0 +1,196 @@
+/*
+   orxonox - the future of 3D-vertical-scrollers
+
+   Copyright (C) 2004 orx
+
+   This program is free software; you can redistribute it and/or modify
+   it under the terms of the GNU General Public License as published by
+   the Free Software Foundation; either version 2, or (at your option)
+   any later version.
+
+### File Specific:
+   main-programmer: christoph
+   co-programmer:
+*/
+
+
+/* this is for debug output. It just says, that all calls to PRINT() belong to the DEBUG_MODULE_NETWORK module
+   For more information refere to https://www.orxonox.net/cgi-bin/trac.cgi/wiki/DebugOutput
+*/
+#define DEBUG_MODULE_NETWORK
+
+#include "handshake.h"
+
+Handshake::Handshake( bool server, int clientId, int networkGameManagerId )
+{
+  /* set the class id for the base object */
+  this->setClassID(CL_HANDSHAKE, "Handshake");
+
+  this->setIsServer(server);
+  this->clientId = clientId;
+  this->networkGameManagerId = networkGameManagerId;
+  this->state = 0;
+  this->isOk = false;
+  this->setOwner(0);
+
+  PRINTF(5)("Handshake created clientId = %d\n", clientId);
+}
+
+void Handshake::writeBytes( const byte * data, int length )
+{
+  PRINTF(5)("Handshake::writeBytes states = %d %d %d %d (%d)\n", hasState( HS_RECVD_INIT ), hasState( HS_RECVD_VER ), hasState( HS_RECVD_HID ), hasState( HS_COMPLETED ), state);
+
+  if ( hasState( HS_COMPLETED ) )
+       return;
+
+  if ( !hasState( HS_RECVD_INIT ) )
+  {
+    if ( length != _INITIAL_DATA_LENGTH )
+    {
+      PRINTF(0)("initial packet has wrong size %d instead of %d\n", length, _INITIAL_DATA_LENGTH);
+      setState( HS_COMPLETED );
+      return;
+    }
+
+    if ( strncmp((char*)data, _INITIAL_DATA, length) )
+    {
+      PRINTF(0)("initial packed does not match\n");
+      setState( HS_COMPLETED );
+      return;
+    }
+
+    setState( HS_RECVD_INIT );
+    PRINTF(0)("got valid initial packet from client %d\n", clientId);
+    return;
+  }
+
+  if ( hasState( HS_RECVD_INIT ) && !hasState( HS_RECVD_VER ) )
+  {
+    if ( length != _ORXONOX_VERSION_LENGTH )
+    {
+      PRINTF(0)("version number packet has wrong size %d instead of %d\n", length, _ORXONOX_VERSION_LENGTH);
+      setState( HS_COMPLETED );
+      return;
+    }
+
+    if ( strncmp((char*)data, _ORXONOX_VERSION, length) )
+    {
+      PRINTF(0)("versions do not match\n");
+      setState( HS_COMPLETED );
+      return;
+    }
+
+    setState( HS_RECVD_VER );
+
+    PRINTF(0)("client %d's version does match\n", clientId);
+    return;
+  }
+
+  if ( !isServer() && hasState( HS_RECVD_VER ) && !hasState( HS_RECVD_HID ) )
+  {
+    if ( length != 2 )
+    {
+      PRINTF(0)("hostID packet has wrong size %d instead of %d\n", length, 1);
+      setState( HS_COMPLETED );
+      return;
+    }
+
+    setState( HS_COMPLETED );
+    setState( HS_RECVD_HID );
+    this->isOk = true;
+    this->newHostId = data[0];
+    this->newNetworkGameManagerId = data[1];
+
+    if ( newHostId == 0 )
+    {
+      setState( HS_WAS_REJECT );
+      isOk = false;
+      PRINTF(0)("Server did not accept handshake!\n");
+    }
+    else
+    {
+      PRINTF(0)("got my hostID: %d and networkGameManagerId: %d\n", newHostId, newNetworkGameManagerId);
+    }
+    return;
+  }
+
+}
+
+int Handshake::readBytes( byte * data, int maxLength, int * reciever )
+{
+  PRINTF(5)("Handshake::readBytes states = %d %d %d %d (%d)\n", hasState( HS_SENT_INIT ), hasState( HS_SENT_VER ), hasState( HS_SENT_HID ), hasState( HS_COMPLETED ), state);
+
+  if ( hasState( HS_COMPLETED ) )
+    return 0;
+
+  if ( !hasState( HS_SENT_INIT ) )
+  {
+    if ( maxLength < _INITIAL_DATA_LENGTH )
+    {
+      PRINTF(0)("buffer too small for _INITIAL_DATA");
+      setState( HS_COMPLETED );
+      return 0;
+    }
+
+    setState( HS_SENT_INIT );
+    memcpy(data, _INITIAL_DATA, _INITIAL_DATA_LENGTH);
+    if ( this->isServer() )
+      *reciever = clientId;
+    return _INITIAL_DATA_LENGTH;
+  }
+
+  if ( hasState( HS_RECVD_INIT ) && hasState( HS_SENT_INIT ) && !hasState( HS_SENT_VER ) )
+  {
+    if ( maxLength < _ORXONOX_VERSION_LENGTH )
+    {
+      PRINTF(0)("buffer too small for version number");
+      setState( HS_COMPLETED );
+      return 0;
+    }
+
+    setState( HS_SENT_VER );
+    memcpy(data, _ORXONOX_VERSION, _ORXONOX_VERSION_LENGTH);
+    if ( this->isServer() )
+      *reciever = clientId;
+    return _ORXONOX_VERSION_LENGTH;
+  }
+
+  if ( isServer() && hasState( HS_RECVD_VER) && hasState( HS_SENT_VER ) && !hasState( HS_SENT_HID ) )
+  {
+    if ( maxLength < 2 )
+    {
+      PRINTF(0)("buffer too small for ID");
+      setState( HS_COMPLETED );
+      return 0;
+    }
+
+    setState( HS_SENT_HID );
+    setState( HS_COMPLETED );
+
+    if ( hasState( HS_DO_REJECT ) )
+    {
+      isOk = false;
+      //memcpy(data, (byte*)0, 4);
+      data[0] = 0;
+    }
+    else
+    {
+      isOk = true;
+      //memcpy(data, &clientId, 4);
+      data[0] = (byte)clientId;
+      data[1] = (byte)networkGameManagerId;
+    }
+    *reciever = clientId;
+    return 2;
+  }
+
+  return 0;
+}
+
+void Handshake::writeDebug( ) const
+{
+}
+
+void Handshake::readDebug( ) const
+{
+}
Index: trunk/src/lib/network/handshake.h
===================================================================
--- trunk/src/lib/network/handshake.h	(revision 6139)
+++ trunk/src/lib/network/handshake.h	(revision 6139)
@@ -0,0 +1,64 @@
+/*!
+ * @file network_stream.h
+ *  implementation of a network pipe
+ */
+
+#ifndef _HANDSHAKE
+#define _HANDSHAKE
+
+#include "base_object.h"
+#include "synchronizeable.h"
+
+#define _INITIAL_DATA "orxonox"
+#define _INITIAL_DATA_LENGTH 7
+
+#define _ORXONOX_VERSION "\x00\x00\x00\x01"
+#define _ORXONOX_VERSION_LENGTH 4
+
+typedef enum HandshakeState {
+  HS_SENT_INIT  = 0x00000001,
+  HS_RECVD_INIT = 0x00000002,
+  HS_SENT_VER   = 0x00000004,
+  HS_RECVD_VER  = 0x00000008,
+  HS_SENT_HID   = 0x00000010,
+  HS_RECVD_HID  = 0x00000020,
+  HS_COMPLETED  = 0x00000040,
+
+  HS_DO_REJECT  = 0x00010000,
+  HS_WAS_REJECT = 0x00020000,
+
+  NUM_STATES
+};
+
+class Handshake : public Synchronizeable
+{
+  public:
+    Handshake(bool server, int clientId = 0, int networkGameManagerId = 0);
+    inline bool       completed(){ return hasState( HS_COMPLETED ); }
+    inline bool       ok(){ return isOk; }
+    inline int        getHostId(){ return newHostId; }
+    inline int        getNetworkGameManagerId(){ return newNetworkGameManagerId; }
+
+    inline void       doReject(){ setState(HS_DO_REJECT); }
+
+    virtual void      writeBytes(const byte* data, int length);
+    virtual int       readBytes(byte* data, int maxLength, int * reciever);
+    virtual void      writeDebug() const;
+    virtual void      readDebug() const;
+
+  private:
+    int               state;
+    int               clientId;
+    int               networkGameManagerId;
+    int               newHostId;
+    int               newNetworkGameManagerId;
+    bool              isOk;
+
+    inline bool       hasState( int a ){ return (state & a) == a; }
+    inline void       setState( int a ){ state = state | a; }
+    inline void       unsetState( int a ){ state = state & (~a); }
+
+};
+
+
+#endif
Index: trunk/src/lib/network/network_game_manager.cc
===================================================================
--- trunk/src/lib/network/network_game_manager.cc	(revision 6139)
+++ trunk/src/lib/network/network_game_manager.cc	(revision 6139)
@@ -0,0 +1,123 @@
+/*
+   orxonox - the future of 3D-vertical-scrollers
+
+   Copyright (C) 2004 orx
+
+   This program is free software; you can redistribute it and/or modify
+   it under the terms of the GNU General Public License as published by
+   the Free Software Foundation; either version 2, or (at your option)
+   any later version.
+
+### File Specific:
+   main-programmer: Benjamin Wuest
+   co-programmer: ...
+*/
+
+
+/* this is for debug output. It just says, that all calls to PRINT() belong to the DEBUG_MODULE_NETWORK module
+   For more information refere to https://www.orxonox.net/cgi-bin/trac.cgi/wiki/DebugOutput
+*/
+#define DEBUG_MODULE_NETWORK
+
+/* include your own header */
+#include "network_game_manager.h"
+
+
+/* using namespace std is default, this needs to be here */
+using namespace std;
+
+/*!
+ * Standard constructor
+ */
+NetworkGameManager::NetworkGameManager()
+{
+  /* set the class id for the base object */
+  this->setClassID(CL_ENTITY_MANAGER, "EntityManager");
+}
+
+/*!
+ * Standard destructor
+ */
+NetworkGameManager::~NetworkGameManager()
+{
+}
+
+
+void NetworkGameManager::writeBytes(const byte* data, int length)
+{
+}
+
+int NetworkGameManager::readBytes(byte* data, int maxLength, int * reciever)
+{
+}
+
+void NetworkGameManager::writeDebug() const
+{
+}
+
+void NetworkGameManager::readDebug() const
+{
+}
+
+
+/*!
+ * Checks whether this is connected to a server or a client
+ * and afterwards creates the needed entity if possible
+ * @param classID: The ID of the class of which an entity should be created
+ */
+void NetworkGameManager::createEntity(int classID)
+{
+}
+
+/*!
+ * Checks whether this is connected to a server or a client
+ * and afterwards removes the specified entity
+ * @param uniqueID: The ID of the entity object which should be removed
+ */
+void NetworkGameManager::removeEntity(int uniqueID)
+{
+}
+
+
+
+/*!
+ * Creates the needed entity on the server if possible
+ * @param classID: The ID of the class of which an entity should be created
+ */
+void NetworkGameManager::requestCreateEntity(int classID)
+{
+}
+
+/*!
+ * Removes the specified entity on the server
+ * @param uniqueID: The ID of the entity object which should be removed
+ */
+void NetworkGameManager::requestRemoveEntity(int uniqueID)
+{
+}
+
+/*!
+ * Creates the needed entity if possible
+ * This function is called if this is a server
+ * @param classID: The ID of the class of which an entity should be created
+ */
+void NetworkGameManager::executeCreateEntity(int classID)
+{
+}
+
+/*!
+ * Removes the specified entity
+ * This function is called if this is a server
+ * @param uniqueID: The ID of the entity object which should be removed
+ */
+void NetworkGameManager::executeRemoveEntity(int uniqueID)
+{
+}
+
+/*!
+ * Checks whether it is possible to create an entity of a given class
+ * @return: true if the entity can be created, false otherwise
+ */
+bool NetworkGameManager::canCreateEntity(int classID)
+{
+}
Index: trunk/src/lib/network/network_game_manager.h
===================================================================
--- trunk/src/lib/network/network_game_manager.h	(revision 6139)
+++ trunk/src/lib/network/network_game_manager.h	(revision 6139)
@@ -0,0 +1,89 @@
+/*!
+ * @file entity_manager.h
+ *  Manages creation and destruction of entities
+ */
+
+#ifndef _NETWORK_GAME_MANGER
+#define _NETWORK_GAME_MANAGER
+
+/* include this file, it contains some default definitions */
+#include "netdefs.h"
+
+/* include base_object.h since all classes are derived from this one */
+#include "synchronizeable.h"
+
+
+
+/**
+ * protocol definition
+ *
+ *  CREATE_ENTITY:      CLASS_ID, UNIQUE_ID, OWNER
+ *  REMOVE_ENTITY:      UNIQUE_ID
+ *
+ *  CREATE_ENTITY_LIST: NUMBER, [CLASS_ID, UNIQUE_ID, OWNER][0..NUMBER]
+ *  REMOVE_ENTITY_LIST: NUMBER, [UNIQUE_ID][0..NUMBER]
+ *
+ *  REQUEST_CREATE:     CLASS_ID
+ *  REQUEST_REMOVE:     UNIQUE_ID
+ *
+ *  REQUEST_SYNC:       UNIQUE_ID
+ *  REQUEST_SYNC_LIST:  NUMBER, [UNIQUE_ID][0..NUMBER]
+ *
+ *
+ */
+
+
+
+
+
+
+
+
+
+
+/*!
+ * a class that can create and remove entities
+ */
+class NetworkGameManager: public Synchronizeable
+{
+  public:
+    NetworkGameManager();
+    ~NetworkGameManager();
+
+    virtual void writeBytes(const byte* data, int length);
+    virtual int readBytes(byte* data, int maxLength, int * reciever);
+    virtual void writeDebug() const;
+    virtual void readDebug() const;
+
+    void createEntity(int classID);
+    void createEntityList(int* classIDList);
+    void removeEntity(int uniqueID);
+    void removeEntityList(int* uniqueIDList);
+
+    void sync(int uniqueID);
+    void syncList(int* uniqueIDList);
+
+
+  private:
+    void requestCreateEntity(int classID);
+    void executeCreateEntity(int classID);
+    void requestCreateEntityList(int* classIDList);
+    void executeCreateEntityList(int* classIDList);
+
+    void requestRemoveEntity(int uniqueID);
+    void executeRemoveEntity(int uniqueID);
+    void requestRemoveEntityList(int* uniqueIDList);
+    void executeRemoveEntityList(int* uniqueIDList);
+
+
+
+    bool canCreateEntity(int classID);
+
+
+
+  private:
+    byte*          inBuffer;
+    byte*          outBuffer;
+};
+
+#endif /*_ENTITY_MANGER*/
Index: trunk/src/lib/network/network_manager.cc
===================================================================
--- trunk/src/lib/network/network_manager.cc	(revision 5997)
+++ trunk/src/lib/network/network_manager.cc	(revision 6139)
@@ -50,4 +50,5 @@
   this->tmpStream = NULL;
   this->hostID = -1;
+  this->bGameServer = false;
 
   PRINTF(0)("NetworkManager created\n");
@@ -95,5 +96,5 @@
   }
 
-  this->tmpStream = new NetworkStream(ipAddress, NET_CLIENT);
+  this->tmpStream = new NetworkStream(ipAddress);
   return 1;
 }
@@ -106,5 +107,6 @@
 int NetworkManager::createServer(unsigned int port)
 {
-  this->tmpStream = new NetworkStream(port, NET_SERVER);
+  this->tmpStream = new NetworkStream(port);
+  this->bGameServer = true;
   SDL_Delay(20);
   return 1;
@@ -120,5 +122,6 @@
 {
   /* creating a new network stream, it will register itself automaticaly to the class list */
-  this->tmpStream = new NetworkStream(address, sync, NET_CLIENT);
+  this->tmpStream = new NetworkStream(address);
+  this->tmpStream->connectSynchronizeable(sync);
 }
 
@@ -132,5 +135,7 @@
   PRINTF(0)("Create a new server socket\n");
   /* creating a new network stream, it will register itself automaticaly to the class list */
-  this->tmpStream = new NetworkStream(port, sync, NET_SERVER);
+  this->tmpStream = new NetworkStream(port);
+  this->tmpStream->connectSynchronizeable(sync);
+  this->bGameServer = true;
 }
 
Index: trunk/src/lib/network/network_manager.h
===================================================================
--- trunk/src/lib/network/network_manager.h	(revision 5997)
+++ trunk/src/lib/network/network_manager.h	(revision 6139)
@@ -45,19 +45,22 @@
     void setHostID(int id);
     /** Returns the hostID @return The hostID of the object */
-    inline int getHostID() { return this->hostID; };
+    inline int getHostID() { return this->hostID; }
+    inline bool isGameServer() { return this->bGameServer; }
 
-  private:
+
     void connectSynchronizeable(Synchronizeable& sync);
     void synchronize();
 
+  private:
     NetworkManager();
 
 
   private:
-    const std::list<BaseObject*>*    netStreamList;            // list with refs to all network streams
-    const std::list<BaseObject*>*    syncList;                 // list of synchronizeables
-    static NetworkManager* singletonRef;           //!< Pointer to the only instance of this Class
-    NetworkStream*         tmpStream;              //!< FIXME: this is only for testing purposes
-    int hostID;                                    //!< The Host-ID of the Manager
+    const std::list<BaseObject*>*    netStreamList;           // list with refs to all network streams
+    const std::list<BaseObject*>*    syncList;                // list of synchronizeables
+    static NetworkManager*           singletonRef;            //!< Pointer to the only instance of this Class
+    NetworkStream*                   tmpStream;               //!< FIXME: this is only for testing purposes
+    int                              hostID;                  //!< The Host-ID of the Manager
+    bool                             bGameServer;             //!< true if it is a server
 
 };
Index: trunk/src/lib/network/network_protocol.cc
===================================================================
--- trunk/src/lib/network/network_protocol.cc	(revision 5997)
+++ trunk/src/lib/network/network_protocol.cc	(revision 6139)
@@ -57,34 +57,24 @@
     * @arg bufferLength: the length of the internal buffer
     * @arg source: reference to the source Synchronizeable object
-    * @arg remoteID: id number of the remote Synchronizeable object
     * @return: the new data length with header (the header data is included into byte* data)
     *          -1 if there isn't enough space in the buffer for the header
 */
-int NetworkProtocol::createHeader(byte* data, int length, int bufferLength, const Synchronizeable& source, unsigned int remoteID)
+int NetworkProtocol::createHeader(byte* data, int length, int bufferLength, const Synchronizeable& source)
 {
-  printf("NetworkProtocol: create header length = %i, bufferLength = %i\n", length, bufferLength);
+  PRINTF(5)("create header length = %i, bufferLength = %i\n", length, bufferLength);
   //If there isn't enough space for the header return -1
   if (length + this->headerLength > bufferLength)
     return -1;
 
-//   for(int i = 0; i < length; i++)
-//     printf("send byte[%i]=%u\n", i, data[i]);
 
-
-  //Create space for the header
+  // FIXME: without move Create space for the header
   for( int i = length - 1; i >= 0; i--)
     data[i + this->headerLength] = data[i];
 
   //Now create the header
-  /* protocol identifier */
-  data[0] = 255;
-  /* version number */
-  data[1] = 0;
   /* sender ID: FIXME: there will be a better ID (for example unique:D)*/
-  data[2] = (byte)source.getClassID();
-  /* receiver ID */
-  data[3] = remoteID;
+  data[0] = (byte)(source.getUniqueID());
   /* data length*/
-  data[4] = length;
+  data[1] = length;
 
 
@@ -100,11 +90,11 @@
 Header NetworkProtocol::extractHeader(byte* data, int length)
 {
-  PRINTF(0)("extract Header\n");
+  PRINTF(5)("extract Header\n");
   //Test if received data can contain a header
   if (length < headerLength)
   {
-    PRINTF(0)("Received data is to short; it can't contain a header!");
+    PRINTF(1)("Received data is to short; it can't contain a header!\n");
     Header h;
-    h.protocol = 0;
+    h.length = 0;
     return h;
   }
@@ -114,21 +104,9 @@
   //&h = data;
 
-  h.protocol = data[0];
-  /* version number */
-  h.version = data[1];
-  /* sender ID: FIXME: there will be a better ID (for example unique:D)*/
-  h.senderID = data[2];
-  /* receiver ID */
-  h.receiverID = data[3];
+  /* unique ID */
+  h.synchronizeableID = data[0];
   /* data length*/
-  h.length = data[4];
+  h.length = data[1];
 
-
-//   for(int i = 0; i < length; i++)
-//     printf("recS byte[%i]=%u\n", i, data[i]);
-
-  //Remove header
-//   for (int i = headerLength; i < length; i++)
-//     data[i - headerLength] = data[i];
 
   return h;
Index: trunk/src/lib/network/network_protocol.h
===================================================================
--- trunk/src/lib/network/network_protocol.h	(revision 5997)
+++ trunk/src/lib/network/network_protocol.h	(revision 6139)
@@ -6,4 +6,5 @@
 #define _NETWORK_PROTOCOL_H
 
+/* include base_object.h since all classes are derived from this one */
 #include "base_object.h"
 
@@ -11,12 +12,7 @@
 #include "netdefs.h"
 
-#define HEADER_LENGTH 1
-
 typedef struct Header
 {
-  byte protocol;
-  byte version;
-  byte senderID;
-  byte receiverID;
+  byte synchronizeableID;
   byte length;
 };
@@ -33,5 +29,5 @@
     ~NetworkProtocol();
 
-    int createHeader(byte* data, int length, int bufferLength, const Synchronizeable& source, unsigned int remoteID);
+    int createHeader(byte* data, int length, int bufferLength, const Synchronizeable& source);
     Header extractHeader(byte* data, int length);
 
Index: trunk/src/lib/network/network_socket.cc
===================================================================
--- trunk/src/lib/network/network_socket.cc	(revision 5997)
+++ trunk/src/lib/network/network_socket.cc	(revision 6139)
@@ -28,5 +28,4 @@
 #include "debug.h"
 
-
 /**
  * Default constructor
@@ -52,6 +51,6 @@
   this->tcpSocket = sock;
 
-  SDL_CreateThread(thread_read, (void*)this);
-  SDL_CreateThread(thread_write, (void*)this);
+  readThread = SDL_CreateThread(thread_read, (void*)this);
+  writeThread = SDL_CreateThread(thread_write, (void*)this);
 }
 
@@ -65,6 +64,15 @@
   outgoingBufferLength = 0;
 
+  readThread = NULL;
+  writeThread = NULL;
+
+
+  thread_write_running = false;
+  thread_read_running = false;
+
   incomingBufferMutex = SDL_CreateMutex();
   outgoingBufferMutex = SDL_CreateMutex();
+
+
   socketMutex = SDL_CreateMutex();
   terminateThread = false;
@@ -89,6 +97,7 @@
  * Default destructor
  */
-NetworkSocket::~ NetworkSocket( )
-{
+NetworkSocket::~NetworkSocket( )
+{
+  this->terminateThread = true;
   /* Quit SDL_net */
   // NOTE: what if other instances of NetworkSocket running?
@@ -99,4 +108,5 @@
   SDL_DestroyMutex(outgoingBufferMutex);
   SDL_DestroyMutex(socketMutex);
+  SDL_DestroyMutex(threadTerminationMutex);
 }
 
@@ -122,6 +132,6 @@
   }
 
-  SDL_CreateThread(thread_read, (void*)this);
-  SDL_CreateThread(thread_write, (void*)this);
+  readThread = SDL_CreateThread(thread_read, (void*)this);
+  writeThread = SDL_CreateThread(thread_write, (void*)this);
 }
 
@@ -152,5 +162,5 @@
 int NetworkSocket::writeBytes(byte * data, int length)
 {
-  PRINTF(0)("NetworkSocket::writeBytes()\n");
+  PRINTF(5)("NetworkSocket::writeBytes()\n");
 #ifdef _USE_OUTGOING_BUFFER
 
@@ -200,5 +210,5 @@
 int NetworkSocket::readBytes(byte * data, int length)
 {
-  PRINTF(0)("NetworkSocket::readBytes()\n");
+  PRINTF(5)("NetworkSocket::readBytes()\n");
   if (data==NULL)
     return 0;
@@ -256,4 +266,6 @@
   NetworkSocket * self = (NetworkSocket*)data;
 
+  self->thread_read_running = true;
+
   while (!self->terminateThread)
   {
@@ -263,5 +275,5 @@
 
     //if buffer is full
-    if (nbytestoread<=0)
+    if (nbytestoread<=0 || !self->tcpSocket)
     {
       SDL_Delay(_MSECONDS_SLEEP_FULL_BUFFER);
@@ -275,5 +287,6 @@
     if (nbytesread<=0)
     {
-      printf("SDLNet_TCP_Recv: %s\n", SDLNet_GetError());
+      if (nbytesread<0)
+        printf("SDLNet_TCP_Recv: %s\n", SDLNet_GetError());
 
       SDL_mutexP(self->socketMutex);
@@ -284,5 +297,5 @@
       SDL_mutexV(self->socketMutex);
       SDL_mutexV(self->incomingBufferMutex);
-      return -1;
+      continue;
     }
 
@@ -295,4 +308,19 @@
   }
 
+  SDL_mutexP(self->threadTerminationMutex);
+  self->thread_read_running = false;
+
+  if ( !self->thread_write_running )
+  {
+    //delete self;
+    SDL_mutexV(self->threadTerminationMutex);
+  }
+  else
+  {
+    SDL_mutexV(self->threadTerminationMutex);
+  }
+
+
+  PRINTF(0)("QUIT READ THREAD\n");
   return 0;
 }
@@ -305,4 +333,6 @@
   NetworkSocket * self = (NetworkSocket*)data;
 
+  self->thread_write_running = true;
+
   while (!self->terminateThread)
   {
@@ -314,5 +344,5 @@
 
     //if buffer is full
-    if (nbytestowrite<=0)
+    if (nbytestowrite<=0 || !self->tcpSocket)
     {
       SDL_Delay(_MSECONDS_SLEEP_EMPTY_BUFFER);
@@ -342,10 +372,24 @@
 
       SDL_mutexV(self->socketMutex);
-      return -1;
+      continue;
     }
 
   }
 
-  printf("QUIT WRITE THREAD\n");
+  SDL_mutexP(self->threadTerminationMutex);
+  self->thread_write_running = false;
+
+  if ( !self->thread_read_running )
+  {
+    //delete self;
+    SDL_mutexV(self->threadTerminationMutex);
+  }
+  else
+  {
+    SDL_mutexV(self->threadTerminationMutex);
+  }
+
+
+  PRINTF(0)("QUIT WRITE THREAD\n");
   return 0;
 }
@@ -353,5 +397,5 @@
 bool NetworkSocket::writePacket( byte * data, int length )
 {
-  PRINTF(0)("NetworkSocket::writePacket()\n");
+  PRINTF(5)("NetworkSocket::writePacket()\n");
   if (length>255)
   {
@@ -368,5 +412,5 @@
 int NetworkSocket::readPacket( byte * data, int maxLength )
 {
-  PRINTF(0)("NetworkSocket::readPacket()\n");
+  PRINTF(5)("NetworkSocket::readPacket()\n");
   if (incomingBufferLength<1)
   {
Index: trunk/src/lib/network/network_socket.h
===================================================================
--- trunk/src/lib/network/network_socket.h	(revision 5997)
+++ trunk/src/lib/network/network_socket.h	(revision 6139)
@@ -63,5 +63,12 @@
   bool terminateThread;
 
+  SDL_mutex* threadTerminationMutex;
   static int thread_read(void * data);
+  bool thread_read_running;
+  bool thread_write_running;
+
+  SDL_Thread*            readThread;
+  SDL_Thread*            writeThread;
+
 #ifdef _USE_OUTGOING_BUFFER
   static int thread_write(void * data);
@@ -74,4 +81,7 @@
   void init();
 
+  //dont make this public use destroy() instead
+  ~NetworkSocket();
+
 public:
 
@@ -79,5 +89,6 @@
   NetworkSocket(IPaddress ip);
   NetworkSocket(TCPsocket sock);
-  ~NetworkSocket();
+  void destroy() { terminateThread = true; };
+
 
   void connectToServer(IPaddress ip);
@@ -87,4 +98,6 @@
   int readPacket(byte * data, int maxLength);
 
+  inline bool isOk() { return tcpSocket!=NULL; }
+
 };
 
Index: trunk/src/lib/network/network_stream.cc
===================================================================
--- trunk/src/lib/network/network_stream.cc	(revision 5997)
+++ trunk/src/lib/network/network_stream.cc	(revision 6139)
@@ -26,6 +26,8 @@
 #include "connection_monitor.h"
 #include "synchronizeable.h"
+#include "network_manager.h"
 #include "list.h"
 #include "debug.h"
+#include "class_list.h"
 
 /* include your own header */
@@ -45,57 +47,36 @@
   /* initialize the references */
   this->type = NET_CLIENT;
-  this->networkSocket = new NetworkSocket();
   this->networkProtocol = new NetworkProtocol();
-  this->synchronizeables = NULL;
   this->connectionMonitor = new ConnectionMonitor();
 }
 
-NetworkStream::NetworkStream(IPaddress& address, NodeType type)
-{
-  this->type = type;
+NetworkStream::NetworkStream(IPaddress& address)
+{
+  this->type = NET_CLIENT;
   this->init();
-  this->networkSocket = new NetworkSocket(address);
+  this->networkSockets.push_back(new NetworkSocket(address));
   this->networkProtocol = new NetworkProtocol();
-  this->synchronizeables = NULL;
   this->connectionMonitor = new ConnectionMonitor();
-}
-
-
-NetworkStream::NetworkStream(unsigned int port, NodeType type)
-{
-  this->type = type;
+
+  Handshake* hs = new Handshake(false);
+  hs->setUniqueID( 0 );
+  this->handshakes.push_back(hs);
+  this->connectSynchronizeable(*hs);
+  PRINTF(0)("NetworkStream: %s\n", hs->getName());
+}
+
+
+NetworkStream::NetworkStream(unsigned int port)
+{
+  this->type = NET_SERVER;
   this->init();
-  this->networkSocket = new NetworkSocket();
-//  this->networkSocket->listen(port);
+  this->serverSocket = new ServerSocket(port);
   this->networkProtocol = new NetworkProtocol();
-  this->synchronizeables = NULL;
   this->connectionMonitor = new ConnectionMonitor();
-}
-
-
-NetworkStream::NetworkStream(IPaddress& address, Synchronizeable& sync, NodeType type)
-    : DataStream()
-{
-  this->type = type;
-  this->init();
-  this->networkSocket = new NetworkSocket(address);
-  this->networkProtocol = new NetworkProtocol();
-  this->synchronizeables = &sync;
-  this->connectionMonitor = new ConnectionMonitor();
+  this->networkSockets.push_back( NULL );
+  this->handshakes.push_back( NULL );
   this->bActive = true;
-}
-
-
-NetworkStream::NetworkStream(unsigned int port, Synchronizeable& sync, NodeType type)
-    : DataStream()
-{
-  this->type = type;
-  this->init();
-  this->networkSocket = new NetworkSocket();
-//  this->networkSocket->listen(port);
-  this->networkProtocol = new NetworkProtocol();
-  this->synchronizeables = &sync;
-  this->connectionMonitor = new ConnectionMonitor();
-  this->bActive = true;
+
+  this->setMaxConnections( 10 );
 }
 
@@ -105,6 +86,7 @@
   /* set the class id for the base object */
   this->setClassID(CL_NETWORK_STREAM, "NetworkStream");
-  this->state = NET_REC_HEADER;
   this->bActive = false;
+  this->serverSocket = NULL;
+  myHostId = 0;
 }
 
@@ -112,9 +94,26 @@
 NetworkStream::~NetworkStream()
 {
-
-  networkSocket->disconnectServer();
-
-  if( this->networkSocket)
-    delete networkSocket;
+  if ( this->serverSocket )
+  {
+    serverSocket->close();
+    delete serverSocket;
+  }
+
+  for (NetworkSocketVector::iterator i = networkSockets.begin(); i!=networkSockets.end(); i++)
+  {
+    if ( *i )
+    {
+      (*i)->disconnectServer();
+      (*i)->destroy();
+    }
+  }
+
+  for (HandshakeVector::iterator i = handshakes.begin(); i!=handshakes.end(); i++)
+  {
+    if ( *i )
+    {
+      delete (*i);
+    }
+  }
 
   delete connectionMonitor;
@@ -125,76 +124,255 @@
 void NetworkStream::connectSynchronizeable(Synchronizeable& sync)
 {
-  this->synchronizeables = &sync;
-  if( this->networkSocket != NULL)
+  this->synchronizeables.push_back(&sync);
+  sync.setNetworkStream( this );
+
+  if( this->networkSockets.size()>0 )
     this->bActive = true;
 }
 
+void NetworkStream::disconnectSynchronizeable(Synchronizeable& sync)
+{
+  this->synchronizeables.remove(&sync);
+
+  if( this->networkSockets.size()<=0 )
+    this->bActive = false;
+}
+
 
 void NetworkStream::processData()
 {
-  int dataLength = 0;
+  if ( this->type == NET_SERVER )
+    this->updateConnectionList();
+  else
+  {
+    if ( networkSockets[0] && !networkSockets[0]->isOk() )
+    {
+      PRINTF(1)("lost connection to server\n");
+
+      //delete networkSockets[i];
+      networkSockets[0]->disconnectServer();
+      networkSockets[0]->destroy();
+      networkSockets[0] = NULL;
+      //TODO: delete handshake from synchronizeable list so i can delete it
+      if ( handshakes[0] )
+        delete handshakes[0];
+      handshakes[0] = NULL;
+    }
+  }
+
+  for (int i = 0; i<handshakes.size(); i++)
+  {
+    if ( handshakes[i] )
+    {
+      if ( handshakes[i]->completed() )
+      {
+        if ( handshakes[i]->ok() )
+        {
+          if ( type != NET_SERVER )
+          {
+            NetworkManager::getInstance()->setHostID( handshakes[i]->getHostId() );
+            myHostId = NetworkManager::getInstance()->getHostID();
+          }
+          PRINT(0)("handshake finished\n");
+          delete handshakes[i];
+          handshakes[i] = NULL;
+          //TODO: replace handshake by entitymanager
+        }
+        else
+        {
+          PRINT(1)("handshake failed!\n");
+          networkSockets[i]->disconnectServer();
+          delete handshakes[i];
+          handshakes[i] = NULL;
+          //TODO: handle error
+        }
+      }
+    }
+  }
+
 
   /* DOWNSTREAM */
-  printf("\nSynchronizeable: %s\n", this->synchronizeables->getName());
-  PRINT(0)("============= DOWNSTREAM:===============\n");
-  /* first of all read the synchronizeable's data: */
-  if( this->isServer())
-    dataLength = this->synchronizeables->readBytes((byte*)downBuffer);
-
-  if( dataLength > 0)
-  {
-    /* send the received data to connectionMonitor */
-    this->connectionMonitor->processPacket((byte*)downBuffer, dataLength);
-
-    dataLength = this->networkProtocol->createHeader((byte*)downBuffer, dataLength, DATA_STREAM_BUFFER_SIZE,
-                 *(this->synchronizeables), 12/* some random number (no real id)*/);
-
-    /* pass the data to the network socket */
- //   dataLength = this->networkSocket->writeBytes((byte*)downBuffer, dataLength);
-    /* check if there was an error */
-    if( dataLength == -1)
-    {
-      PRINTF(0)("Error in writing data to the NetworkSocket\n");
-    }
-  }
-
+
+  int dataLength;
+  int reciever;
+  Header header;
+  for (SynchronizeableList::iterator it = synchronizeables.begin(); it!=synchronizeables.end(); it++)
+  {
+    //TODO: remove items from synchronizeables if they dont exist
+    if ( (*it)!=NULL && (*it)->getOwner() == myHostId )
+    {
+      do {
+        reciever = 0;
+        dataLength = (*it)->readBytes(downBuffer, DATA_STREAM_BUFFER_SIZE, &reciever);
+
+
+        if ( dataLength<=0 ){
+          reciever = 0;
+          continue;
+        }
+
+        dataLength = networkProtocol->createHeader((byte*)downBuffer, dataLength, DATA_STREAM_BUFFER_SIZE, static_cast<const Synchronizeable&>(*(*it)));
+
+        //FIXME: this is a hack, find a better way
+        Header* header = (Header*)downBuffer;
+        if ( header->synchronizeableID<100 )
+          header->synchronizeableID = 0;
+
+        if ( dataLength<=0 )
+          continue;
+
+        if ( reciever!=0 )
+        {
+          if ( networkSockets[reciever] != NULL )
+          {
+            PRINTF(5)("write %d bytes to socket %d\n", dataLength, reciever);
+            networkSockets[reciever]->writePacket(downBuffer, dataLength);
+          }
+          else
+          {
+            PRINTF(1)("networkSockets[reciever] == NULL\n");
+          }
+        }
+        else
+        {
+          for ( int i = 0; i<networkSockets.size(); i++)
+          {
+            if ( networkSockets[i] != NULL )
+            {
+              PRINTF(5)("write %d bytes to socket %d\n", dataLength, reciever);
+              networkSockets[i]->writePacket(downBuffer, dataLength);
+            }
+          }
+        }
+
+      } while( reciever!=0 );
+    }
+    else
+    {
+      PRINTF(0)("synchronizeables == NULL");
+    }
+  }
 
   /* UPSTREAM */
-  dataLength = 0;
-  PRINT(0)("============== UPSTREAM:================\n");
-  /* first of all read the next Orxonox Network Header */
-
-  if( this->state == NET_REC_HEADER)
-  {
-//    dataLength = this->networkSocket->readBlock((byte*)upBuffer, sizeof(Header));
-    if( dataLength == sizeof(Header))
-    {
-      this->packetHeader = this->networkProtocol->extractHeader((byte*) upBuffer , dataLength);
-      printf("NetworkStream::processData() - Got Header: Protocol %u, Version: %u, Sender: %u, Receiver: %u, Length: %u\n",
-             this->packetHeader.protocol, this->packetHeader.version, this->packetHeader.senderID,
-             this->packetHeader.receiverID, this->packetHeader.length);
-      /* FIXME: what if it was no this->packetHeader? catch? eg: the protocol identifier, receiver id*/
-
-      this->state = NET_REC_DATA;
-    }
-  }
-  if( this->state == NET_REC_DATA)
-  {
-    /* now read the data */
-//    dataLength = this->networkSocket->readBlock((byte*)upBuffer, this->packetHeader.length);
-    /* check if the data is available and process it if so */
-    if( dataLength == this->packetHeader.length)
-    {
-      printf("NetworkStream::processData() - Got Data: %i bytes\n", dataLength);
-      /* send the received data to connectionMonitor */
-      this->connectionMonitor->processPacket((byte*)upBuffer, this->packetHeader.length);
-      /* now pass the data to the sync object */
-      if( !this->isServer())
-        this->synchronizeables->writeBytes((byte*)upBuffer, this->packetHeader.length);
-
-      this->state = NET_REC_HEADER;
-    }
-  }
-
-
-}
+
+  for ( int i = 0; i<networkSockets.size(); i++)
+  {
+    if ( networkSockets[i] )
+    {
+      do {
+        dataLength = networkSockets[i]->readPacket(upBuffer, DATA_STREAM_BUFFER_SIZE);
+
+        if ( dataLength<=0 )
+          continue;
+
+        PRINTF(5)("read %d bytes from socket\n", dataLength);
+        header = networkProtocol->extractHeader(upBuffer, dataLength);
+        dataLength -= sizeof(header);
+
+        if ( dataLength != header.length )
+        {
+          PRINTF(1)("packetsize in header and real packetsize do not match! %d:%d\n", dataLength, header.length);
+          continue;
+        }
+
+        if ( header.synchronizeableID == 0 )
+        {
+          header.synchronizeableID = i;
+        }
+
+        for (SynchronizeableList::iterator it = synchronizeables.begin(); it!=synchronizeables.end(); it++)
+        {
+          if ( *it && (*it)->getUniqueID()==header.synchronizeableID )
+            (*it)->writeBytes(upBuffer+sizeof(header), dataLength);
+        }
+
+      } while ( dataLength>0 );
+    }
+  }
+}
+
+void NetworkStream::updateConnectionList( )
+{
+  //check for new connections
+
+  NetworkSocket* tempNetworkSocket = serverSocket->getNewSocket();
+
+  if ( tempNetworkSocket )
+  {
+    int clientId;
+    if ( freeSocketSlots.size() >0 )
+    {
+      clientId = freeSocketSlots.back();
+      freeSocketSlots.pop_back();
+      networkSockets[clientId] = tempNetworkSocket;
+      handshakes[clientId] = new Handshake(true, clientId);
+      handshakes[clientId]->setUniqueID(clientId);
+    } else
+    {
+      clientId = networkSockets.size();
+      networkSockets.push_back(tempNetworkSocket);
+      Handshake* tHs = new Handshake(true, clientId);
+      tHs->setUniqueID(clientId);
+      handshakes.push_back(tHs);
+    }
+
+    if ( clientId > this->maxConnections )
+    {
+      handshakes[clientId]->doReject();
+      PRINTF(0)("Will reject client %d because there are to many connections!\n", clientId);
+    }
+    else
+
+    PRINTF(0)("New Client: %d\n", clientId);
+
+    this->connectSynchronizeable(*handshakes[clientId]);
+  }
+
+
+  //check if connections are ok else remove them
+  for ( int i = 1; i<networkSockets.size(); i++)
+  {
+    if ( networkSockets[i] && !networkSockets[i]->isOk() )
+    {
+      //TODO: tell EntityManager that this player left the game
+      PRINTF(0)("Client is gone: %d\n", i);
+
+      //delete networkSockets[i];
+      networkSockets[i]->disconnectServer();
+      networkSockets[i]->destroy();
+      networkSockets[i] = NULL;
+      //TODO: delete handshake from synchronizeable list so i can delete it
+      if ( handshakes[i] )
+        delete handshakes[i];
+      handshakes[i] = NULL;
+
+      if ( i == networkSockets.size()-1 )
+      {
+        networkSockets.pop_back();
+        handshakes.pop_back();
+      }
+      else
+      {
+        freeSocketSlots.push_back(i);
+      }
+    }
+  }
+
+
+}
+
+void NetworkStream::setMaxConnections( int n )
+{
+  if ( !this->isServer() )
+  {
+    PRINTF(1)("Cannot set maxConnections because I am no server.\n");
+  }
+  if ( this->networkSockets.size() > 1 )
+  {
+    PRINTF(1)("Cannot set maxConnections because there are already %d connections.\n", this->networkSockets.size());
+    return;
+  }
+  this->maxConnections = n;
+}
+
+
Index: trunk/src/lib/network/network_stream.h
===================================================================
--- trunk/src/lib/network/network_stream.h	(revision 5997)
+++ trunk/src/lib/network/network_stream.h	(revision 6139)
@@ -7,20 +7,21 @@
 #define _NETWORK_STREAM
 
+#include <vector>
+#include <list>
+
 #include "data_stream.h"
 #include "network_protocol.h"
+#include "server_socket.h"
+#include "handshake.h"
 
 class Synchronizeable;
 class NetworkSocket;
+class ServerSocket;
 class ConnectionMonitor;
 class NetworkProtocol;
 
-
-//<! The state of the NetworkStream
-typedef enum NetStat {
-  NET_REC_HEADER = 0,                          //!< Waiting for header
-  NET_REC_DATA,                                //!< Waiting for data
-
-  NUM_STATES                                   //!< Number of states
-};
+typedef std::list<Synchronizeable*>  SynchronizeableList;
+typedef std::vector<NetworkSocket*>  NetworkSocketVector;
+typedef std::vector<Handshake*>      HandshakeVector;
 
 
@@ -30,16 +31,18 @@
   public:
     NetworkStream();
-    NetworkStream(IPaddress& address, NodeType type);
-    NetworkStream(unsigned int port, NodeType type);
+    NetworkStream(IPaddress& address);
+    NetworkStream(unsigned int port);
 
-    NetworkStream(IPaddress& address, Synchronizeable& sync, NodeType type);
-    NetworkStream(unsigned int port, Synchronizeable& sync, NodeType type);
     ~NetworkStream();
     void init();
 
     void connectSynchronizeable(Synchronizeable& sync);
+    void disconnectSynchronizeable(Synchronizeable& sync);
 
     inline bool isServer() const { return (this->type == NET_SERVER)? true:false; }
     inline bool isActive() const { return this->bActive; }
+
+    inline int getMaxConnections(){ return maxConnections; }
+    void setMaxConnections( int n );
 
     virtual void processData();
@@ -48,10 +51,17 @@
     NetworkProtocol*       networkProtocol;
     ConnectionMonitor*     connectionMonitor;
-    Synchronizeable*       synchronizeables;
-    NetworkSocket*         networkSocket;
+    SynchronizeableList    synchronizeables;
+    NetworkSocketVector    networkSockets;
+    HandshakeVector        handshakes;
+    ServerSocket*          serverSocket;
     int                    type;
-    int                    state;
     Header                 packetHeader;
     bool                   bActive;
+    std::list<int>         freeSocketSlots;
+
+    int                    myHostId;
+    int                    maxConnections;
+
+    void updateConnectionList();
 };
 #endif /* _NETWORK_STREAM */
Index: trunk/src/lib/network/server_socket.cc
===================================================================
--- trunk/src/lib/network/server_socket.cc	(revision 5997)
+++ trunk/src/lib/network/server_socket.cc	(revision 6139)
@@ -110,6 +110,13 @@
 
 
-NetworkSocket ServerSocket::getNewSocket( )
+NetworkSocket* ServerSocket::getNewSocket( )
 {
+  if ( !listenSocket )
+  {
+    PRINTF(1)("listenSocket == NULL! Maybe you forgot to call listen()\n");
+    close();
+    return NULL;
+  }
+
   TCPsocket sock = SDLNet_TCP_Accept(listenSocket);
 
@@ -120,6 +127,17 @@
   else
   {
-    return NetworkSocket(sock);
+    return new NetworkSocket(sock);
   }
 }
 
+void ServerSocket::close( )
+{
+  if ( listenSocket )
+  {
+    SDLNet_TCP_Close( listenSocket );
+    listenSocket = NULL;
+  }
+
+  _isListening = false;
+}
+
Index: trunk/src/lib/network/server_socket.h
===================================================================
--- trunk/src/lib/network/server_socket.h	(revision 5997)
+++ trunk/src/lib/network/server_socket.h	(revision 6139)
@@ -39,5 +39,7 @@
     ~ServerSocket();
     bool listen( unsigned int port );
-    NetworkSocket getNewSocket( void );
+    NetworkSocket* getNewSocket( void );
+    void close();
+    inline bool isOk(){ return listenSocket!=NULL; }
 };
 
Index: trunk/src/lib/network/synchronizeable.cc
===================================================================
--- trunk/src/lib/network/synchronizeable.cc	(revision 5997)
+++ trunk/src/lib/network/synchronizeable.cc	(revision 6139)
@@ -15,6 +15,10 @@
 */
 
+#define DEBUG_MODULE_NETWORK
+
 #include "synchronizeable.h"
 #include "netdefs.h"
+#include "network_manager.h"
+#include "network_stream.h"
 
 
@@ -25,6 +29,7 @@
 {
 
-  //owner = ?;
-  //hostID = ?;
+  owner = 0;
+  hostID = NetworkManager::getInstance()->getHostID();
+  uniqueID = -1;
   //state = ?;
 
@@ -44,5 +49,8 @@
  */
 Synchronizeable::~Synchronizeable()
-{}
+{
+  if ( this->networkStream )
+    this->networkStream->disconnectSynchronizeable(*this);
+}
 
 /**
@@ -50,11 +58,15 @@
  */
 void Synchronizeable::writeBytes(const byte* data, int length)
-{}
+{
+  PRINTF(1)("Synchronizeable::writeBytes was called\n");
+}
 
 /**
  *  read data from NetworkStream
  */
-int Synchronizeable::readBytes(byte* data)
-{}
+int Synchronizeable::readBytes(byte* data, int maxLength, int * reciever)
+{
+  PRINTF(1)("Synchronizeable::readBytes was called\n");
+}
 
 
@@ -65,7 +77,4 @@
 void Synchronizeable::readDebug() const
 {}
-
-
-
 
 
@@ -111,2 +120,5 @@
   return this->state & STATE_OUTOFSYNC == STATE_OUTOFSYNC;
 }
+
+
+
Index: trunk/src/lib/network/synchronizeable.h
===================================================================
--- trunk/src/lib/network/synchronizeable.h	(revision 5997)
+++ trunk/src/lib/network/synchronizeable.h	(revision 6139)
@@ -19,4 +19,6 @@
 #define STATE_OUTOFSYNC 2
 
+class NetworkStream;
+
 
 class Synchronizeable : virtual public BaseObject
@@ -29,23 +31,27 @@
 
     virtual void      writeBytes(const byte* data, int length);
-    virtual int       readBytes(byte* data);
+    virtual int       readBytes(byte* data, int maxLength, int * reciever);
     virtual void      writeDebug() const;
     virtual void      readDebug() const;
-    
-    
-    
-    
-    
-    void setIsServer(bool isServer);
-    void setIsOutOfSync(bool outOfSync);
+
+    void setIsServer( bool isServer );
+    void setIsOutOfSync( bool outOfSync );
     bool isServer();
     bool isOutOfSync();
+    void setUniqueID( int id ){ uniqueID = id; }
+    int  getUniqueID() const { return uniqueID; };
+    void requestSync( int hostID ){ this->synchronizeRequests.push_back( hostID ); }
+
+    inline int getOwner(){ return owner; }
+    inline void setOwner(int owner){ this->owner = owner; }
+
+    inline void setNetworkStream(NetworkStream* stream) { this->networkStream = stream; }
 
   private:
 
     int               uniqueID;
-    
-    
-    
+
+
+
     //static std::vector<Synchronizeable*> classList;
     int owner;
@@ -54,4 +60,6 @@
     std::list<int> synchronizeRequests;
 
+    NetworkStream* networkStream;
+
   };
 #endif /* _SYNCHRONIZEABLE_H */
