00001
00002
00003
00004
00005
00006
00007
00008
00009
00010
00011
00012
00013
00014
00015
00016
00017
00018
00019
00020
00021 #include "SocketTCP.h"
00022
00023 SocketTCP::SocketTCP(int socket){
00024 mSocket=socket;
00025 }
00026
00027 SocketTCP::SocketTCP(unsigned int port) throw(SocketException) : Socket(port){
00028 int retour;
00029 struct sockaddr_in adresse;
00030 mSocket=socket(AF_INET,SOCK_STREAM,0);
00031 if (mSocket<0) throw(SocketException(1));
00032 adresse.sin_family=AF_INET;
00033 adresse.sin_port = htons((u_short)port);
00034 adresse.sin_addr.s_addr=INADDR_ANY;
00035 retour = bind(mSocket,(struct sockaddr *)&adresse,sizeof(adresse));
00036 if (retour<0) throw(SocketException(2));
00037 listen(mSocket,7);
00038 }
00039
00040 SocketTCP::SocketTCP(string ad, unsigned int port) throw(SocketException) : Socket(ad,port){
00041 struct sockaddr_in adresse;
00042 struct hostent *recup;
00043 mSocket=socket(AF_INET, SOCK_STREAM, 0);
00044 if (mSocket < 0) throw(SocketException(1));
00045 recup = gethostbyname(ad.c_str());
00046 if (recup == NULL) throw(SocketException(3));
00047 memcpy((char *)&adresse.sin_addr, (char *)recup->h_addr, recup->h_length);
00048 adresse.sin_family = AF_INET;
00049 adresse.sin_port = htons((u_short) port);
00050 if (connect(mSocket, (struct sockaddr *)&adresse, sizeof(adresse)) == -1) throw(SocketException(4));
00051 }
00052
00053 Socket* SocketTCP::Accept() throw(SocketException){
00054 int socket;
00055 struct sockaddr_in socketEntrante;
00056 socklen_t taille=sizeof(socketEntrante);
00057 socket=accept(mSocket,(struct sockaddr*) &socketEntrante,&taille);
00058 if(socket==-1) throw(SocketException(5));
00059 Socket *s=new SocketTCP(socket);
00060 return s;
00061 }
00062
00063 SocketTCP::SocketTCP(Socket *s) : Socket(s){
00064 }
00065
00066
00067 SocketTCP::SocketTCP(const SocketTCP &s){
00068 mSocket=s.mSocket;
00069 mCryptage=s.mCryptage;
00070 }
00071
00072 void SocketTCP::operator=(const SocketTCP &s){
00073 mSocket=s.mSocket;
00074 mCryptage=s.mCryptage;
00075 }
00076
00077 SocketTCP::~SocketTCP(){
00078 close(mSocket);
00079 }
00080
00081 void SocketTCP::Envoyer(string msg) const throw(SocketException){
00082 int s=send(mSocket,(mCryptage->Crypter(msg)).c_str(),msg.length(),0);
00083 if(s==-1){
00084 throw(SocketException(6));
00085 }
00086 }
00087
00088 string SocketTCP::Ecouter() throw(SocketException){
00089 char buffer[BUFSIZ];
00090 int s=recv(mSocket,buffer,BUFSIZ,0);
00091 if (s==-1) throw(SocketException(7));
00092 else if(s==0) throw(SocketException(9));
00093 else {
00094 buffer[s]=0;
00095 return mCryptage->Decrypter(buffer);
00096 }
00097 }