00001 #include "client.h"
00002
00003 GameClient::GameClient() : netMessageChannel() {
00004 con_state = NOT_CONNECTED;
00005 server_name = NULL;
00006 server_port = SERVER_LISTEN_PORT;
00007 }
00008
00009 GameClient::~GameClient() {
00010 netMessage quit(MSG_CLIENT_LOGOFF, serverID, myID);
00011 sendMessage(&quit);
00012 close();
00013 con_state = NOT_CONNECTED;
00014 }
00015
00016 void GameClient::connect_to(char* sname, int port = SERVER_LISTEN_PORT) {
00017 if (!open(false)) {
00018 fprintf(stderr, "could not open port");
00019 return;
00020 }
00021 setBlocking(false);
00022 if (connect(sname, port) == -1) {
00023 fprintf(stderr, "could not connect to %s:%i\n", sname, port);
00024 return;
00025 }
00026 netMessage login_msg(MSG_LOGIN, 0, 0);
00027 login_msg.puti(strlen(login_name)+1);
00028 login_msg.puts(login_name);
00029 login_msg.puti(strlen(login_pass)+1);
00030 login_msg.puts(login_pass);
00031 if (!sendMessage(&login_msg)) {
00032 fprintf(stderr, "error sending login msg");
00033 return;
00034 }
00035 con_state = TRYING_CON;
00036 }
00037
00038 bool GameClient::disconnect() {
00039 if (con_state != NOT_CONNECTED) {
00040 netMessage quit(MSG_CLIENT_LOGOFF, serverID, myID);
00041 sendMessage(&quit);
00042 close();
00043 con_state = NOT_CONNECTED;
00044 return true;
00045 }
00046 return false;
00047 }
00048
00049 void GameClient::handle_login_ok(const netMessage &msg) {
00050 float srv_time;
00051 *msg.getfv(&srv_time, 1);
00052
00053 con_state = CONNECTED;
00054 }
00055
00056 void GameClient::handle_login_fail(const netMessage &msg) {
00057 con_state = NOT_CONNECTED;
00058 }
00059
00060 void GameClient::handleMessage(const netMessage &msg) {
00061 if (*msg.getType() == MSG_SERVER_DOWN) {
00062 fprintf("ERROR: server going down\n");
00063 }
00064 switch (con_state) {
00065 case NOT_CONNECTED:
00066 fprintf(stderr, "WARN: ignoring msg (%i) from %i\n",
00067 *msg.getType(), *msg.getFromID());
00068 break;
00069 case TRYING_CON:
00070 switch(*msg.getType()) {
00071 case MSG_LOGIN_OK:
00072 handle_login_ok(msg);
00073 break;
00074 case MSG_LOGIN_FAIL:
00075 handle_login_fail(msg);
00076 break;
00077 }
00078 break;
00079 case CONNECTED:
00080
00081
00082
00083
00084
00085
00086
00087
00088
00089 break;
00090 }
00091 }