00001 /* 00002 * The Mana World 00003 * Copyright (C) 2004 The Mana World Development Team 00004 * 00005 * This file is part of The Mana World. 00006 * 00007 * This program is free software; you can redistribute it and/or modify 00008 * it under the terms of the GNU General Public License as published by 00009 * the Free Software Foundation; either version 2 of the License, or 00010 * any later version. 00011 * 00012 * This program is distributed in the hope that it will be useful, 00013 * but WITHOUT ANY WARRANTY; without even the implied warranty of 00014 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 00015 * GNU General Public License for more details. 00016 * 00017 * You should have received a copy of the GNU General Public License 00018 * along with this program; if not, write to the Free Software 00019 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA 00020 */ 00021 00022 #ifndef EA_NETWORK_H 00023 #define EA_NETWORK_H 00024 00025 #include <SDL_net.h> 00026 #include <SDL_thread.h> 00027 00028 #include <map> 00029 #include <string> 00030 00035 #define CLIENT_PROTOCOL_VERSION 1 00036 00037 class MessageHandler; 00038 class MessageIn; 00039 00040 class Network 00041 { 00042 public: 00043 friend int networkThread(void *data); 00044 friend class MessageOut; 00045 00046 Network(); 00047 00048 ~Network(); 00049 00050 bool connect(const std::string &address, short port); 00051 00052 void disconnect(); 00053 00054 void registerHandler(MessageHandler *handler); 00055 00056 void unregisterHandler(MessageHandler *handler); 00057 00058 void clearHandlers(); 00059 00060 int getState() const { return mState; } 00061 00062 const std::string &getError() const { return mError; } 00063 00064 bool isConnected() const { return mState == CONNECTED; } 00065 00066 int getInSize() const { return mInSize; } 00067 00068 void skip(int len); 00069 00070 bool messageReady(); 00071 00072 MessageIn getNextMessage(); 00073 00074 void dispatchMessages(); 00075 00076 void flush(); 00077 00078 // ERROR replaced by NET_ERROR because already defined in Windows 00079 enum { 00080 IDLE, 00081 CONNECTED, 00082 CONNECTING, 00083 DATA, 00084 NET_ERROR 00085 }; 00086 00087 private: 00088 static Network *instance(); 00089 00090 void setError(const std::string &error); 00091 00092 Uint16 readWord(int pos); 00093 00094 bool realConnect(); 00095 00096 void receive(); 00097 00098 TCPsocket mSocket; 00099 00100 std::string mAddress; 00101 short mPort; 00102 00103 char *mInBuffer, *mOutBuffer; 00104 unsigned int mInSize, mOutSize; 00105 00106 unsigned int mToSkip; 00107 00108 int mState; 00109 std::string mError; 00110 00111 SDL_Thread *mWorkerThread; 00112 SDL_mutex *mMutex; 00113 00114 typedef std::map<Uint16, MessageHandler*> MessageHandlers; 00115 typedef MessageHandlers::iterator MessageHandlerIterator; 00116 MessageHandlers mMessageHandlers; 00117 00118 static Network *mInstance; 00119 }; 00120 00121 #endif