socketCtrl.cpp

00001 /*
00002   TCP/IPソケット管理
00003   Satofumi KAMIMURA
00004   $Id$
00005 */
00006 
00007 #include "socketCtrl.h"
00008 
00009 
00010 void SocketCtrl::bufferInit(int buffer_size) {
00011   recv_buffer = new RingBuffer<char>(buffer_size);
00012 }
00013 
00014 
00015 SocketCtrl::SocketCtrl(const char *host, Uint16 port, unsigned int buffer_size)
00016   : is_disconnected(false) {
00017   IPaddress ip;
00018   SDLNet_ResolveHost(&ip, host, port);
00019   tcp_socket = SDLNet_TCP_Open(&ip);
00020   bufferInit(buffer_size);
00021 }
00022 
00023 
00024 SocketCtrl::SocketCtrl(TCPsocket tcpsocket, unsigned int buffer_size)
00025   : is_disconnected(false), tcp_socket(tcpsocket) {
00026   bufferInit(buffer_size);
00027 }
00028 
00029 
00030 SocketCtrl::~SocketCtrl(void) {
00031   if (tcp_socket) {
00032     SDLNet_TCP_Close(tcp_socket);
00033     tcp_socket = NULL;
00034   }
00035 }
00036 
00037 
00038 void SocketCtrl::disconnect(void) {
00039   is_disconnected = true;
00040 }
00041 
00042 
00043 bool SocketCtrl::is_connect(void) {
00044   return ((tcp_socket != NULL) && !is_disconnected) ? true : false;
00045 }
00046 
00047 
00048 TCPsocket& SocketCtrl::getTCPsocket(void) {
00049   return tcp_socket;
00050 }
00051 
00052 
00053 void SocketCtrl::check(void) {
00054   if (is_connect() && SDLNet_SocketReady(tcp_socket)) {
00055     int maxlen = recv_buffer->free_size();
00056     maxlen = (maxlen > BUFSIZ) ? BUFSIZ : maxlen;
00057     char buffer[BUFSIZ];
00058     int n = SDLNet_TCP_Recv(tcp_socket, buffer, maxlen);
00059     if (n <= 0) {
00060       is_disconnected = true;
00061       return;
00062     }
00063     recv_buffer->put(buffer, n);
00064   }
00065 }
00066 
00067 
00068 int SocketCtrl::recv(void *area, unsigned int maxlen) {
00069   check();
00070   if (!is_connect()) {
00071     return -1;
00072   }
00073 
00074   int len = (recv_buffer->size() > maxlen) ? maxlen : recv_buffer->size();
00075   if (len == 0) {
00076     return 0;
00077   }
00078   recv_buffer->get((char *)area, maxlen);
00079   
00080   return len;
00081 }
00082 
00083 
00084 int SocketCtrl::send(const void *area, int len) {
00085   check();
00086   if (!is_connect()) {
00087     return -1;
00088   }
00089   
00090   return SDLNet_TCP_Send(tcp_socket, (void *)area, len);
00091 }
00092 
00093 
00094 unsigned long SocketCtrl::size(void) {
00095   check();
00096   return recv_buffer->size();
00097 }
00098 

Generated on Mon Apr 13 22:52:01 2009 by  doxygen 1.5.7.1