summaryrefslogtreecommitdiff
path: root/2005/i/robert/src/socket/socket_text.cc
blob: da8a23bfd59db8918003ac9ae1a7ff5dc8d37849 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
// socket_text.cc
// robert - programme du robot 2005. {{{
//
// Copyright (C) 2005 Dufour J�r�my
//
// This program is free software; you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation; either version 2 of the License, or
// (at your option) any later version.
// 
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
//
// Contact :
//        Web: %WEB%
//      Email: <dufourj@efrei.fr>
// }}}

#include "socket_text.hh"

#include "server_socket.hh"
#include "address.hh"

#include <sstream>
#include <stdexcept>
#include <iterator>
#include <fcntl.h>

/// Taille maximum du header
static const unsigned max_header_size = 10;

/// Constructeur du serveur
SocketText::SocketText (ServerSocket &ss)
: recvBufPos_ (0), numMessageBuffer_ (0)
{
    headBuf_.resize (max_header_size);
    socket_ = ss.accept ();
}

/// Constructeur du serveur avec addresse
SocketText::SocketText (ServerSocket &ss, Address &a)
: recvBufPos_ (0), numMessageBuffer_ (0)
{
    headBuf_.resize (max_header_size);
    socket_ = ss.accept (a);
}

/// Constructeur du client
SocketText::SocketText (const Address &a)
: recvBufPos_ (0), numMessageBuffer_ (0)
{
    headBuf_.resize (max_header_size);
    // Cr�ation du socket
    socket_ = socket (AF_INET, SOCK_STREAM, 0);
    if (socket_ == -1)
	throw std::runtime_error ("Erreur de cr�ation de socket");
    // Connexion au serveur
    if (connect (socket_, a.getSockaddr (), sizeof (sockaddr_in)) == -1)
	throw std::runtime_error ("Erreur de connexion au serveur");
}

/// Envoie d'un buffer de donn�es.
SocketText &
SocketText::operator<< (const DataBuffer &d)
{
    // Copie du buffer
    DataBuffer db (d);
    // R�cup�ration de la taille du message
    unsigned size = db.size ();
    // Donn�es du buffer
    std::vector<char> data (size);
    // On y place les donn�es dedans
    db.read ((uint8_t*) &data[0], size);
    // Encode les donn�es et le places dans le buffer d'envoie
    encode (&data[0], size, db.type ());
    return *this;
}

/// Reception d'un buffer de donn�es.
SocketText &
SocketText::operator>> (DataBuffer &d)
{
    if (numMessageBuffer_ > 0)
      {
	// R�cup�ration des informations du message qu'on veut retirer
	unsigned int size = messList_.begin ()->size;
	d.setType (messList_.begin ()->type);
	// R�cup�ration du message depuis le buffer
	std::vector <char> v (size);
	std::memcpy (&v[0], &recvBuf_[0], size);
	// Ecriture des donn�es dans le buffer
	d.write ((uint8_t*) &v[0], v.size ());
	// Suppression du message du buffer
	recvBuf_.erase (recvBuf_.begin (), recvBuf_.begin () + size);
	messList_.erase (messList_.begin ());
	bufferOldSize_ -= size;
	bufferCurSize_ -= size;
	recvBufPos_ -= size;
	numMessageBuffer_--;
      }
    return *this;
}

/// Envoie des donn�es du buffer.
int
SocketText::send (void)
{
    int status;
    status = ::send (socket_, &sendBuf_[0], sendBuf_.size (), MSG_NOSIGNAL);
    if (status == -1 && errno != EWOULDBLOCK)
      {
	throw std::runtime_error ("Erreur de send de socket");
      }
    if (status >= 0)
      {
	if (status != 0)
	    sendBuf_.erase (sendBuf_.begin (), sendBuf_.begin () + status);
	return status;
      }
    return -1;
}

/// Encodage du message (rajout du header)
void
SocketText::encode (const char *data, const int size,
		    const DataBuffer::dataType_e type)
{
    // Cr�ation du header (1H4242H)
    std::ostringstream o;
    // Rajout du type
    if (!(o << type))
	throw std::runtime_error ("Erreur de convertion int -> string");
    o << "H";
    if (!(o << size ))
	throw std::runtime_error ("Erreur de convertion int -> string");
    o << "H";
    // Recopie du header dans le buffer
    std::string s = o.str ();
    std::string::const_iterator sEnd = s.end ();
    unsigned int compt = 0;
    std::string::const_iterator i = s.begin ();
    // Ecriture d'un header de taille fixe
    while (compt < max_header_size)
      {
	if (i != sEnd)
	  {
	    sendBuf_.push_back (*i);
	    i++;
	  }
	else
	    sendBuf_.push_back ('H');
	compt++;
      }
    // Rajout des donn�es dans le buffer
    for (int i = 0; i < size; i++)
	sendBuf_.push_back (data[i]);
}

/// D�codage du header.
int
SocketText::decode (void)
{
    mess_t header;
    header.type = (DataBuffer::dataType_e) std::atoi (&headBuf_[0]);
    header.size = std::atoi (&headBuf_[2]);
    messList_.push_back (header);
    return header.size;
}

/// Reception de donn�es dans un vecteur.
bool
SocketText::recv ()
{
    // FIXME C'est KK
    int status;
    static unsigned int headerPos = 0;

    // On n'a pas re�u encore de quoi faire un header
    if (headerPos < max_header_size)
      {
	status = ::recv (socket_, &headBuf_[headerPos],
			 max_header_size - headerPos, MSG_NOSIGNAL);
	if (status == -1 && errno != EWOULDBLOCK)
	    throw std::runtime_error ("Erreur de send de socket");
	if (status > 0)
	    headerPos += status;
      }
    // D�codage du header
    if (headerPos == max_header_size)
      {
	bufferOldSize_ = recvBuf_.size ();
	bufferCurSize_ = bufferOldSize_ + decode ();
	recvBuf_.resize (bufferCurSize_);
	headerPos ++;
      }
    // R�cup�ration du message lui-m�me
    if (headerPos > max_header_size)
      {
	status = ::recv (socket_, &recvBuf_[recvBufPos_],
			 bufferCurSize_ - recvBufPos_, MSG_NOSIGNAL);
	if (status == -1 && errno != EWOULDBLOCK)
	    throw std::runtime_error ("Erreur de send de socket");
	if (status > 0)
	    recvBufPos_ += status;
	if (recvBufPos_ == bufferCurSize_)
	  {
	    headerPos = 0;
	    numMessageBuffer_++;
	  }
      }
    return numMessageBuffer_ > 0;
}

/// Changement du bloquant non/bloquant.
void
SocketText::nonblock (bool flag)
{
    // R�cup�ration de l'ancien flag.
    int old = fcntl (socket_, F_GETFL, 0);
    if (old == -1)
	throw std::runtime_error ("Erreur de fcntl");
    // Change le flag.
    if (flag)
	old |= O_NONBLOCK;
    else
	old &= ~O_NONBLOCK;
    // Ecrit le nouveau flag.
    if (fcntl (socket_, F_SETFL, old) == -1)
	throw std::runtime_error ("Erreur de fcntl");
}