28 #include <sys/socket.h> 31 #include <rtt/Logger.hpp> 38 #if MSGLENGTH * 3 > BUFLENGTH 39 #error "MSGLENGTH too long" 43 #define SEND_OPTIONS 0 45 #define SEND_OPTIONS MSG_NOSIGNAL 49 const unsigned int bufsize = 2048;
50 class sockbuf :
public std::streambuf
59 char* ptr =
new char[bufsize];
60 setp(ptr, ptr + bufsize);
74 mainClass->socket, SOL_SOCKET, SO_NOSIGPIPE, &value,
sizeof(value)))
76 Logger::log() << Logger::Error <<
"Error setting socket option. Continuing." << Logger::endl;
94 if (pbase() == epptr())
112 void put_char(
int chr)
114 Logger::log() << Logger::Error <<
"Socket::put_char is unimplemented" << Logger::endl;
119 if (pbase() != pptr())
121 int length = (pptr() - pbase());
122 char *buffer =
new char[length + 1];
124 strncpy(buffer, pbase(), length);
125 buffer[length] =
'\0';
128 if( length && ::send ( mainClass->socket, buffer, length, SEND_OPTIONS ) == -1 )
130 mainClass->rawClose();
132 setp(pbase(), epptr());
141 Socket::Socket(
int socketID ) :
142 std::ostream( new sockbuf(this) ),
143 socket(socketID), begin(0), ptrpos(0), end(0)
163 return isValid() && lineAvailable();
166 bool Socket::lineAvailable()
168 int flags = fcntl(socket,F_GETFL);
169 fcntl(socket,F_SETFL,flags | O_NONBLOCK);
170 int ret =recv(socket,buffer,MSGLENGTH,MSG_PEEK);
173 for(
unsigned int i=0;i<MSGLENGTH;++i)
174 if( buffer[i] ==
'\n'){
207 void Socket::checkBufferOverflow()
209 if( end + MSGLENGTH >= BUFLENGTH ) {
210 if( ptrpos - begin > MSGLENGTH ) {
211 Logger::log() << Logger::Error <<
"Message length violation" << Logger::endl;
214 memcpy( buffer, &buffer[begin], end - begin);
225 if(0>recv(socket,buffer,
sizeof(
char[ptrpos+1]),MSG_WAITALL))
228 return std::string(buffer,ptrpos);
268 void Socket::rawClose()
280 int _socket = socket;
286 int flags = fcntl( _socket, F_GETFL, 0 );
291 fcntl( _socket, F_SETFL, flags | O_NONBLOCK );
292 ::send ( _socket,
"104 Bye bye", 11, SEND_OPTIONS );
void close()
Close the connection.
The Orocos Component Library.
std::string readLine()
Read a line from the socket.
bool isValid() const
Check wether the state of the socket is valid or not.
bool dataAvailable()
Check wether there is new data available.