Скачать 169.83 Kb.
|
Санкт-Петербургский Государственный Электротехнический Университет «ЛЭТИ» Кафедра МО ЭВМ ОТЧЕТ Лабораторная работа №4 ПРОЕКТИРОВАНИЕ И РЕАЛИЗАЦИЯ СИСТЕМЫ КЛАССОВ, ОБЕСПЕЧИВАЮЩИХ ОБМЕН СООБЩЕНИЯМИ В ОБЪЕКТНО-ОРИЕНТИРОВАННОЙ ПРОГРАММЕ Выполнил Монько А.О. Группа 7304 Преподаватель Смольянинов А.В. Санкт-Петербург 2010 г. Задание 1. Формулирование основной идеи архитектуры В схеме обмена Сервер — Клиент — Сервер, присутствует 1 сервер и несколько клиентов. Обмен сообщениями происходит только между сервером и клиентом. При этом действуют связи: «сервер — клиент» и «клиент — сервер». Сервер может обмениваться сообщениями только с зарегистрированными клиентами. А клиент только с зарегистрированными серверами. Объекты:
Будем различать 3 типа сообщений:
Процесс обмена сообщениями: 1. Сервер может отослать сообщение одному клиенту, используя его идентификационный номер или отослать сообщение всем клиентам. 2. Клиент анализирует пришедшее сообщение. 3. Если это подтверждение о приеме от сервера, то никаких действий не следует. 4. Иначе клиент отправляет серверу сообщение – подтверждение о приеме, после чего производит анализ параметров сообщения: кода сообщения (идентификатора выполняемого действия) и информации, переданной сервером (возможно, данные для выполнения заданного действия). 5. Выполнив указанное сервером действие, клиент отправляет серверу отчет – подтверждение о выполнении действия. 6. Сервер в свою очередь отсылает клиенту подтверждение получения сообщения. 2. Разработанные классы на C++ Класс «Сообщение» class CMessage { private: unsigned int FromID; unsigned int ToID; double Info; int Type;/* тип сообщения: 0 - подтверждение приема 1 - отчет о выполнение > 1 - запрос действия */ unsigned int direction; /* направление передачи: 0 - сервер->клиент 1 - клиент->сервер */ static unsigned int debug; static unsigned int total; const unsigned int id; static unsigned int current; public: CMessage(unsigned int _FromID = 0, unsigned int _ToID = 0, int _Type = 0, double _Info = 0, unsigned int _dir = 0); CMessage(const CMessage& msg); ~CMessage(); unsigned int GetFromID() const { return FromID; } unsigned int GetToID() const { return ToID; } unsigned int GetType() const { return Type; } double GetInfo() const { return Info; } unsigned int GetDirection() const { return direction; } void SetFromID(unsigned int _FromID); void SetToID(unsigned int _ToID); void SetType(unsigned int _Type); void SetInfo(double _Info); void SetDirection(unsigned int _dir); const char* InterpritateType (unsigned int type); void Print () const; static void SetDebug (unsigned int d) { debug = d; } unsigned int GetID () { return id; } static unsigned int GetCurrent () { return current; } static unsigned int GetTotal () { return total; } static unsigned int Get_debug() { return debug; } }; _____________________________________________________________________ #include "CMsg.h" #include unsigned int CMessage :: current = 0; unsigned int CMessage :: total = 0; unsigned int CMessage :: debug = 0; CMessage :: CMessage(unsigned int _FromID, unsigned int _ToID, int _Type, double _Info, unsigned int _dir) : FromID(_FromID), ToID(_ToID), Type(_Type), Info(_Info), id(++total) { ++current; if (debug) { cout << InterpritateType(Type)<< " Message with id = " << id << " created"< if (direction == 0) cout << "From server with id = " < if (direction == 0) cout << "From server with id = " < if (direction == 0) cout << "From server with id = " < }break; case 1 :{ return "Report"; }break; default:{ return "Action"; } } } void CMessage :: Print () const{ cout < if (direction == 0) cout << "from server with id = " < #include "CServer.h" #include "CMsg.h" #include class CServer; class CClient { private: static unsigned int debug; static unsigned int total; const unsigned int id; static unsigned int current; //список серверов на которых зарегестрирован клиент CircleList public: CClient(); ~CClient(); CServer* GetServerByID(unsigned int _id); //получить сервер по ID unsigned int ServerCount() const; //кол-во зарегестрированных серверов void Register(CServer *server); // Зарегестрироваться на сервере void Unregister(unsigned int _id); // Сняться с регистрации void UnregisterAll(); //Сняться с регистрации со всех серверов void SendMessage(CMessage *msg, unsigned int _id); // отправить сообщение серверу void SendMessage(unsigned int _type, double _info, unsigned int _id); // отправить сообщение серверу void ReceiveMessage(CMessage *msg); // Получить сообщение void Action(unsigned int _type, const float _info); void Print() const; static void SetDebug (unsigned int d) { debug = d; } unsigned int GetID () { return id; } static unsigned int GetCurrent () { return current; } static unsigned int GetTotal () { return total; } static unsigned int Get_debug() { return debug; } }; _______________________________________________________________________________ #include "CClient.H" #include "CList.h" #include "CListN.h" #include #include unsigned int CClient :: current = 0; unsigned int CClient :: total = 0; unsigned int CClient :: debug = 0; CClient :: CClient() : id(++total) { ++current; if (debug) { cout << "Client with id = " << id << " is created" < << "total = " << total << ", current = " << current< } } CClient :: ~CClient() { UnregisterAll(); --current; if (debug) { cout << "Client with id = " << id << " is deleted" < << "total = " << total << ", current = " << current< } } CServer* CClient :: GetServerByID(unsigned int _id) { ServerList.GetFirst(); for (int i = 0; i < ServerList.GetSize(); i++,ServerList.NextCur()) { if (ServerList.GetElemByNum(i)->GetValue()->GetID() == _id) return ServerList.GetCur()->GetValue(); } return 0; } unsigned int CClient :: ServerCount() const { return ServerList.GetSize(); } void CClient :: Register(CServer *server) { if (server == NULL) { cout << "Client with id = "< <<"Failed to register on server due to wrong address"< } else { if (GetServerByID(server->GetID()) != NULL) { cout << "Client with id = "< <<"Already registered on server with id = "< } else { ServerList.Append(new CLNode if (server->GetClientByID(id) == NULL) { server->Register(this); cout << "Client with id = " << id << " was registered on server with id = " << server->GetID()< } } } } void CClient::Unregister(unsigned int _id) { CServer *server = GetServerByID(_id); if (server == NULL) { cout << "Client with id = "< } else { ServerList.ExcludeCur(); if (server->GetClientByID(id) != NULL) { server->Unregister(id); cout << "Client with id = "< } else { int tlen = ServerList.GetSize(); for (int i = 0; i < tlen;i++) { Unregister(ServerList.GetElemByNum(i)->GetValue()->GetID()); } cout << "Client with id = "< } } void CClient::SendMessage(CMessage *msg, unsigned int _id) { CServer *server = GetServerByID(_id); if (server != NULL) { msg->SetFromID(id); msg->SetToID(_id); msg->SetDirection(1); server->ReceiveMessage(msg); // cout << "Client with id = "< getch(); // delete msg; } } void CClient::SendMessage(unsigned int _type, double _info, unsigned int _id) { CServer *server = GetServerByID(_id); CMessage *msg = new CMessage; if (server != NULL) { msg->SetFromID(id); msg->SetToID(_id); msg->SetType(_type); msg->SetInfo(_info); msg->SetDirection(1); server->ReceiveMessage(msg); // cout << "Client with id = "< getch(); } delete msg; } void CClient::ReceiveMessage(CMessage *msg) { CServer *server = GetServerByID(msg->GetFromID()); if (server != NULL) { cout < <<"from server with id = "< msg->Print(); getch(); if (msg->GetType() > 1) { /*CMessage *msg1 = new CMessage(*msg); msg1->SetType(0); //код подтверждения приёма сообщения msg1->SetDirection(1); SendMessage(msg1, server->GetID()); //отправка подтверждения о приёме //сообщения */ Action (msg->GetType(), msg->GetInfo()); //отправка подтверждения о выполнении действия CMessage *msg2 = new CMessage(); msg2->SetType(1); msg2->SetDirection(1); SendMessage(msg2, server->GetID()); //delete msg2; } } else { cout << "Client with id = " < } //delete msg; } void CClient::Action(unsigned int _code, const float _info) { switch (_code) { case 2: cout << "Client is handling action with code = "<<_code< << "And parametrs = "<< _info< case 3: cout << "Client is handling action with code = "<<_code< << "And parametrs = "<< _info<< endl< break; default: cout << "Client could not handle action with code = "<<_code< << "case of unknown code "<< endl< break; } } void CClient :: Print() const { cout << "Client : "< << "ID = "< << "Current number of clients = "< << "Number of registered servers = "< << "List of servers : "< cout << "List is empty"< } else { ServerList.GetFirst(); for (int i = 0;i < ServerList.GetSize(); i++,ServerList.NextCur()) { cout << "#"<< i+1<<" Server, ID = "< } } } _______________________________________________________________________________ Класс «Сервер» #include "CMSG.H" #include "CCLIENT.H" #include class CClient; class CServer { private: static unsigned int debug; static unsigned int total; const unsigned int id; static unsigned int current; CircleList public: CServer(); ~CServer(); CClient* GetClientByID(unsigned int _id); unsigned int Client_Count() const; void Register(CClient *client); void Unregister(unsigned int _id); void UnregisterAll(); void SendMessage(CMessage *msg, unsigned int _id); void SendMessage(unsigned int _type, double _info, unsigned int _id); void SendMessageToAll(CMessage *msg); void SendMessageToAll(unsigned int _type, double _info); void ReceiveMessage(CMessage *msg); void Print() const; static void SetDebug (unsigned int d) { debug = d; } unsigned int GetID () { return id; } static unsigned int GetCurrent () { return current; } static unsigned int GetTotal () { return total; } static unsigned int Get_debug() { return debug; } }; _______________________________________________________________________________ #include "CList.h" #include "CListN.h" #include "CServer.H" #include #include unsigned int CServer :: current = 0; unsigned int CServer :: total = 0; unsigned int CServer :: debug = 0; CServer :: CServer() : id(++total) { ++current; if (debug) { cout <<"Server with id = "< cout << "Total number of servers = "< <<"Current number of servers = "< } } CServer :: ~CServer() { UnregisterAll(); --current; if (debug) { cout <<"Server with id = "< cout << "Total number of servers = "< <<"Current number of servers = "< } } CClient* CServer :: GetClientByID(unsigned int _id) { ClientList.GetFirst(); for (int i = 0; i < ClientList.GetSize();i++,ClientList.NextCur()) { if (ClientList.GetCur()->GetValue()->GetID() == _id) return ClientList.GetCur()->GetValue(); } return 0; } unsigned int CServer :: Client_Count() const { return ClientList.GetSize(); } void CServer :: Register(CClient *client) { if (client == NULL) { cout << "Server with id = "< <<"Failed to register client due to wrong address"< } else { if (GetClientByID(client->GetID()) != NULL) { cout << "Client with id = "< <<"Already registered on server with id = "< } else { ClientList.Append(new CLNode if (client->GetServerByID(id) == NULL) { client->Register(this); cout << "Client with id = " << client->GetID() << " was registered on server with id = " << id< } } } } void CServer :: Unregister(unsigned int _id) { CClient* client = GetClientByID(_id); if (client == NULL) { cout << "Client with id = "<<_id<< " can not unregister from server with id = "< <<"cause it does not registered on it"< } else { ClientList.ExcludeCur(); if (client->GetServerByID(id) != NULL) { client->Unregister(id); cout << "Client with id = "< } } } void CServer ::UnregisterAll() { if (ClientList.GetSize() == 0) { cout << "There are already no registered clients exists"< } else { ClientList.GetFirst(); int tlen = ClientList.GetSize(); for (int i = 0; i < tlen;i++) { // ClientList.GetFirst(); /* ClientList.ExcludeCur();*/Unregister(ClientList.GetFirst()->GetValue()->GetID()); } cout << "Server with id = "< } } void CServer :: SendMessage(CMessage *msg, unsigned int _id) { CClient *client = GetClientByID(_id); if (client != NULL) { msg->SetFromID(id); msg->SetToID(_id); msg->SetDirection(0); client->ReceiveMessage(msg); // cout << "Server with id = "< getch(); // delete msg; } } void CServer :: SendMessageToAll(unsigned int _type, double _info) { CMessage* msg = new CMessage(id,1,_type,_info,0); if (ClientList.GetSize() != 0) { msg->SetDirection(0); int tlen = ClientList.GetSize(); for (int i = 0; i < tlen; i ++) { msg->SetFromID(id); msg->SetToID(ClientList.GetElemByNum(i)->GetValue()->GetID()); ClientList.GetElemByNum(i)->GetValue()->ReceiveMessage(msg); } // cout << "Server with id = "< } else { cout << "Server with id = " << id<< "could not send messages to clients"< <<"cause they are not registered on it"< getch(); } // delete msg; } void CServer :: SendMessageToAll(CMessage *msg) { SendMessageToAll(msg->GetType(),msg->GetInfo()); } void CServer :: SendMessage(unsigned int _type, double _info, unsigned int _id) { CClient *client = GetClientByID(_id); CMessage *msg = new CMessage; if (client != NULL) { msg->SetFromID(id); msg->SetToID(_id); msg->SetType(_type); msg->SetInfo(_info); msg->SetDirection(0); client->ReceiveMessage(msg); // cout << "Server with id = "< getch(); } delete msg; } void CServer :: ReceiveMessage(CMessage *msg) { CClient* client = GetClientByID(msg->GetFromID()); if (client != NULL) { cout << "Server with id = "< <<"from client with id = "< msg->Print(); getch(); if (msg->GetType() > 0) { CMessage *msg1 = new CMessage(*msg); msg1->SetType(0); //код подтверждения приёма сообщения msg1->SetDirection(0); SendMessage(msg1, client->GetID()); delete msg1; } } else { cout << "Server with id = " < } // delete msg; } void CServer::Print() const{ cout << "Server : "< << "ID = "< << "Current number of servers = "< << "Number of registered clients = "< << "List of clients : "< cout << "List is empty"< } else { ClientList.GetFirst(); for (int i = 0;i < ClientList.GetSize(); i++,ClientList.NextCur()) { cout << "#"<< i+1<<" Server, ID = "< } } } _______________________________________________________________________________ «Тестирующая программа» #include "CMsg.h" #include "CServer.h" #include "CClient.h" #include "CList.h" #include #include int main(int argc, char* argv[]) { clrscr(); cout << endl< cout << "Programm is modeling of Server->Client->Server message exchange"< << "with confirmation of Client->Server interaction."< << "Programmed by : Artyom Mon'ko"< << "----------------Press any key to continue or ESC to exit----------------"< int key = getch(); if (key == 27) return 0; // Waiting for some action else break; } int flag = 1; char* buffer = new char[80]; int menu = 0; CServer server; CircleList while (flag) { cout << "1.Create Client"< << "2.Registrate on server"< << "3.Registrate all clients on server"< << "4.Unregistrate client from server"< << "5.Unregistrate all clients from server"< << "6.Send message from server to client"< << "7.Send message from server to all clients"< << "8.Print clients info"< << "9.Print all clients info"< << "10.Exit"< if ((atoi(buffer) == 0) || (atoi(buffer) < 1 || atoi(buffer) > 10)) { cout << "Invalid input, try again : "< continue; } else { menu = (int)atoi(buffer); switch (menu) { case 1: { CClient* cl = new CClient; if (cl) { clients.Append(new CLNode cout << "New client added with id : "< // delete cl; } break; } case 2: { int tid = 1; cout << "Enter id of client, u want to register : "; while (1) { cin >> buffer; if (atoi(buffer) == 0 && buffer[0] != '0') { cout << "Invalind input, try again : "; continue; } else break; } tid = atoi(buffer); for (int i = 0;i < clients.GetSize();i++) { if (clients.GetElemByNum(i)->GetValue()->GetID() == tid) { server.Register(clients.GetElemByNum(i)->GetValue()); break; } } break; } case 3: { for (int i = 0;i < clients.GetSize();i++) server.Register(clients.GetElemByNum(i)->GetValue()); break; } case 4: { int tid = 1; cout << "Enter id of client, u want to unregister : "; while (1) { cin >> buffer; if (atoi(buffer) == 0 && buffer[0] != '0') { cout << "Invalind input, try again : "; continue; } else break; } tid = atoi(buffer); for (int i = 0;i < clients.GetSize();i++) { if (clients.GetElemByNum(i)->GetValue()->GetID() == tid) { server.Unregister(tid); break; } } break; } case 5: { server.UnregisterAll(); break; } case 6: { int tid = 1, tcode = 2; float tinfo = 0; cout << "Enter id of client, u want to send message to : "; while (1) { cin >> buffer; if (atoi(buffer) == 0 && buffer[0] != '0') { cout << "Invalind input, try again : "; continue; } else break; } tid = atoi(buffer); cout << "Enter code of message, u want to send : "; while (1) { cin >> buffer; if (atoi(buffer) == 0 && buffer[0] != '0') { cout << "Invalind input, try again : "; continue; } if (atoi(buffer) < 2) { cout << "Action code is > 2"< continue; } else break; } tcode = atoi(buffer); cout << "Enter the info field : "; while (1) { cin >> buffer; if (atoi(buffer) == 0 && buffer[0] != '0') { cout << "Invalind input, try again : "; continue; } else break; } tinfo = atof(buffer); server.SendMessage(new CMessage(server.GetID(),tid,tcode,tinfo,0),tid); break; } case 7: { int tid = 1, tcode = 2; float tinfo = 0; cout << "Enter code of message, u want to send : "; while (1) { cin >> buffer; if (atoi(buffer) == 0 && buffer[0] != '0') { cout << "Invalind input, try again : "; continue; } if (atoi(buffer) < 2) { cout << "Action code is > 2"< continue; } else break; } tcode = atoi(buffer); cout << "Enter the info field : "; while (1) { cin >> buffer; if (atoi(buffer) == 0 && buffer[0] != '0') { cout << "Invalind input, try again : "; continue; } else break; } tinfo = atof(buffer); server.SendMessageToAll(tcode,tinfo); break; } case 8: { int tid = 1; cout << "Enter id of client, which info u want to look : "; while (1) { cin >> buffer; if (atoi(buffer) == 0 && buffer[0] != '0') { cout << "Invalind input, try again : "; continue; } else break; } tid = atoi(buffer); for (int i = 0;i < clients.GetSize();i++) { if (clients.GetElemByNum(i)->GetValue()->GetID() == tid) { clients.GetElemByNum(i)->GetValue()->Print(); getch(); break; } } break; } case 9: { for (int i = 0;i < clients.GetSize();i++) { clients.GetElemByNum(i)->GetValue()->Print(); cout < getch(); } break; } case 10: { flag = 0; break; } } } } } 3. Количественные характеристики Общее количество классов в программе: 5 Количество новых классов: 3 Количество измененных классов: 1 Количество классов без изменения: 1 Количество файлов на классы: 10 Общее количество файлов: 11 Общее количество строк: 860 4.Результаты тестов 1)Клиенты ID = 1,2,3,4 Зарегистрируем клиентов 1,3,4 и пошлем им сообщение с кодом 2 и параметром 2.6 Сообщение дошло только до клиентов 1,3,4 но не до клиента 2. 2)Клиенты ID = 1,2,3 Зарегистрируем всех клиентов и пошлем клиенту 3 сообщение с кодом 2 и параметром 3.2 Снимем с регистрации клиентов 2,3 и пошлем всем оставшимся сообщение с кодом 3 и параметром 2.1 - сообщение пришло только клиенту 1. 3)Клиенты ID = 1,2 Зарегистрируем всех клиентов и пошлем клиенту 1 сообщение с кодом 3 и параметром 2.1 Снимем с регистрации клиента 2 и добавим клиента ID = 3 Пошлем всем клиентам сообщение с кодом 2 и параметром 0.4 - сообщение дошло клиентам 1,3. |
Отчет по преддипломной практике На тему: «Проектирование программного... Целью работы является проектирование программного человеко-машинного интерфейса для социально-ориентированной системы поддержки очного... | Пояснительная записка На тему: «Проектирование программного пользовательского... На тему: «Проектирование программного пользовательского интерфейса для электронной социально-ориентированной системы поддержки очного... | ||
Анализ посещенного урока Наименование прорабатываемой на занятиях темы знакомство с объектно-ориентированным языком программирования Visual Basic. Лабораторная... | Odmg: 10 лет спустя Целью данной работы является построение высокоэффективной объектно ориентированной системы управления базами данных (оосубд), которая... | ||
Разработка приложения "Выбор банка" (Курсовая работа) Цель курсовой работы: проектирование и программная реализация информационной системы «Выбор банка», с помощью средств Microsoft Visual... | Объектно-ориентированное программирование на примере размножения и развития живых организмов Данная работа представляет собой методическую разработку четырёх уроков информатики, посвящённых объектно-ориентированному программированию.... | ||
Самостоятельная работа по курсу Информатика и икт для групп, обучающихся... Системы, образованные взаимодействующими элементами; состояния элементов, обмен информацией между элементами, сигналы | Типы сетей (Локальная, Intranet, Extranet; Глобальная) Сеть это совокупность устройств, соединенных по определенным правилам и обеспечивающих надежный обмен информацией. Любые сети, в... | ||
«Проектирование программного пользовательского интерфейса для электронной... Тема I: Методологический характер дисциплины «Исследование социально-экономических и политических процессов» | Удк 378: 303 тестирование как инновационная форма контроля Целью работы является проектирование программного человеко-машинного интерфейса для социально-ориентированной системы поддержки очного... | ||
Лабораторная работа №4 по дисциплине: «Информационно-поисковые системы» Работа заключается в сравнительном изучении заданных глобальных ипс сети Интернет вербального типа | Перед Вами задания по биологии. На их выполнение отводится 45 минут. Внимательно читайте задания Целью работы является проектирование программного человеко-машинного интерфейса для социально-ориентированной системы поддержки очного... | ||
Лабораторная работа № Лабораторная работа №1. Изучение основных возможностей программного продукта Яндекс. Сервер. Установка окружения, установка и настройка... | Биология 7 класс Отдел Настоящие Грибы. Лабораторная работа №1 «Строение плесневого гриба мукора». Лабораторная работа №2 «Строение дрожжей» | ||
Отчет о лабораторной работе методы и средства анализа данных по теме:... «Лабораторная работа с системой анализа данных Weka. Сравнение методов классификации» | Отчет о лабораторной работе методы и средства анализа данных по теме:... «Лабораторная работа с системой анализа данных Weka. Сравнение методов классификации» |