| 1 | /*************************************************************************** |
| 2 | * Copyright (C) 2006 by Gerd v. Egidy * |
| 3 | * gve@intra2net.com * |
| 4 | * * |
| 5 | * This library is free software; you can redistribute it and/or modify * |
| 6 | * it under the terms of the GNU Lesser General Public License version * |
| 7 | * 2.1 as published by the Free Software Foundation. * |
| 8 | * * |
| 9 | * This library is distributed in the hope that it will be useful, * |
| 10 | * but WITHOUT ANY WARRANTY; without even the implied warranty of * |
| 11 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * |
| 12 | * GNU Lesser General Public License for more details. * |
| 13 | * * |
| 14 | * You should have received a copy of the GNU Lesser General Public * |
| 15 | * License along with this program; if not, write to the * |
| 16 | * Free Software Foundation, Inc., * |
| 17 | * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. * |
| 18 | ***************************************************************************/ |
| 19 | |
| 20 | #include <string> |
| 21 | #include <sstream> |
| 22 | |
| 23 | #include "connection.hxx" |
| 24 | |
| 25 | namespace libt2n |
| 26 | { |
| 27 | |
| 28 | connection::packet_size_indicator connection::bytes_available() |
| 29 | { |
| 30 | // max packet size is unsigned int |
| 31 | |
| 32 | // no size information -> no packet |
| 33 | if (buffer.size() < sizeof(unsigned int)) |
| 34 | return false; |
| 35 | |
| 36 | packet_size_indicator psize=*((packet_size_indicator*)(buffer.data())); |
| 37 | |
| 38 | // enough data for one packet in buffer? |
| 39 | if (buffer.size() < sizeof(unsigned int)+psize) |
| 40 | return false; |
| 41 | |
| 42 | // ok, full packet there |
| 43 | return true; |
| 44 | } |
| 45 | |
| 46 | bool connection::get_packet(std::string& data) |
| 47 | { |
| 48 | packet_size_indicator psize; |
| 49 | |
| 50 | if ((psize=bytes_available())) |
| 51 | { |
| 52 | data.assign(buffer,sizeof(unsigned int),psize); |
| 53 | buffer.erase(0,sizeof(unsigned int)+psize); |
| 54 | return true; |
| 55 | } |
| 56 | else |
| 57 | return false; |
| 58 | } |
| 59 | |
| 60 | void connection::write(const std::string& data) |
| 61 | { |
| 62 | // prepend packet size to data |
| 63 | packet_size_indicator psize=data.size(); |
| 64 | std::string send_data(data); |
| 65 | send_data.insert(0,(char*)psize,sizeof(packet_size_indicator)); |
| 66 | |
| 67 | real_write(send_data); |
| 68 | } |
| 69 | |
| 70 | |
| 71 | |
| 72 | } |