123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990 |
- #include "Serveur.h"
- Serveur::Serveur(int port, int nbrClient): m_port(port), m_nbrClient(nbrClient)
- {
- #ifdef WIN32
- m_erreur = WSAStartup(MAKEWORD(2,2), &m_WSAData);
- #else
- m_erreur = 0;
- #endif // WIN32
- m_sock.recsize = sizeof(m_sock.sin);
- m_csock = new Sock[m_nbrClient];
- for(int i = 0;i<m_nbrClient;i++)
- {
- m_csock[i].recsize = sizeof(m_csock[i].sin);
- }
- }
- Serveur::~Serveur()
- {
- #ifdef WIN32
- WSACleanup();
- #endif // WIN32
- std::cout << "Fermeture des sockets clientes" << std::endl;
- for(int i = 0;i<m_nbrClient;i++)
- closesocket(m_csock[i].sock);
- std::cout << "Fermeture de la socket serveur" << std::endl;
- closesocket(m_sock.sock);
- std::cout << "Fermeture du serveur termine" << std::endl;
- }
- bool Serveur::rendreUtilisable()
- {
- if(!m_erreur)
- {
- m_sock.sock = socket(AF_INET, SOCK_STREAM, 0);// SOCK_STREAM pour TCP/IP, SOCK_DGRAM pour UDP/IP
- if(m_sock.sock != INVALID_SOCKET)
- {
- std::cout << "La socket " << m_sock.sock << " est maintenant ouverte en mode TCP/IP" << std::endl;
- m_sock.sin.sin_addr.s_addr = htonl(INADDR_ANY);
- m_sock.sin.sin_family = AF_INET;
- m_sock.sin.sin_port = htons(m_port);
- if(bind(m_sock.sock, (SOCKADDR*)&m_sock.sin, m_sock.recsize) != SOCKET_ERROR)
- {
- std::cout << "Listage du port " << m_port << "..." << std::endl;
- if(listen(m_sock.sock, 5) != SOCKET_ERROR)
- {
- std::cout << "Patientez pendant que les " << m_nbrClient << " clients se connectent sur le port " << m_port << "..." << std::endl;
- for(int i = 0;i<m_nbrClient;i++)
- {
- m_csock[i].sock = accept(m_sock.sock, (SOCKADDR*)&m_csock[i].sin, &m_csock[i].recsize);// renvoi INVALID_SOCKET si il y a un probleme
- if(m_csock[i].sock != INVALID_SOCKET)
- {
- std::cout << "Un clien se connect avec la socket " << m_csock[i].sock << " de " << inet_ntoa(m_csock[i].sin.sin_addr) << " : " << htons(m_csock[i].sin.sin_port) << std::endl;
- }
- else
- return false;
- }
- }
- else
- return false;
- }
- else
- return false;
- }
- else
- return false;
- }
- else
- return false;
- return true;
- }
- void Serveur::envoyer(void* donnee, int indice, int tailleByte)
- {
- if(tailleByte != 0)
- send(m_csock[indice].sock, (char*)donnee, tailleByte, 0);
- else
- send(m_csock[indice].sock, (char*)donnee, sizeof(donnee), 0);
- }
- void Serveur::recevoir(void* donnee, int indice, int tailleByte)
- {
- if(tailleByte != 0)
- recv(m_csock[indice].sock, (char*)donnee, tailleByte, 0);
- else
- recv(m_csock[indice].sock, (char*)donnee, sizeof(donnee), 0);
- }
|