TcpConnection.cpp

Go to the documentation of this file.
00001 /*
00002 
00003 $Header$
00004 
00005 */
00006 
00007 #include <stdio.h>
00008 #include <stdlib.h>
00009 #include <unistd.h>
00010 #include <String.h>
00011 #include <netdb.h>
00012 #include <fcntl.h>
00013 #include <sys/time.h>
00014 #include <arpa/inet.h>
00015 #include <sys/socket.h>
00016 #include <errno.h>
00017 #include <sys/ioctl.h>
00018 
00019 #include "Error.h"
00020 
00021 #include "TcpConnection.h"
00022 
00023 // Public methods.
00024 
00025 TcpConnection::TcpConnection(const String &host, const String &service) : Connection()
00026 {
00027   struct sockaddr_in peer;
00028   int sock;
00029   int res;
00030 
00031   _status = TCP_CONNECTION_STATUS_DISCONNECTED;
00032 
00033   DEBUG("TCP connection to host '%s' with service '%s'.", CSTRING(host), CSTRING(service));
00034   if (FAILED(res = setAddress(CSTRING(host), CSTRING(service), "tcp", &peer))) {
00035     failure(ERROR_BACKTRACE(res));
00036     return;
00037   }
00038 
00039   if ((sock = ::socket(AF_INET, SOCK_STREAM, 0)) < 0) {
00040     failure(ERROR(MSG_SOCKET_CANNOT_CREATE, strerror(errno)));
00041     return;
00042   }
00043 
00044   if (FAILED(res = setup(sock, &peer)))
00045     failure(ERROR_BACKTRACE(res));
00046 }
00047 
00048 TcpConnection::TcpConnection(int socket, struct sockaddr_in *addr) : Connection(socket, addr)
00049 {
00050   _status = TCP_CONNECTION_STATUS_DISCONNECTED;
00051 }
00052 
00053 TcpConnection::~TcpConnection()
00054 {
00055 }
00056 
00057 int TcpConnection::connect()
00058 {
00059   if (::connect(_socket, (struct sockaddr *)&(_peer), sizeof(_peer)))
00060     return ERROR(MSG_SOCKET_CANNOT_CONNECT, strerror(errno));
00061 
00062   return OK;
00063 }
00064 
00065 int TcpConnection::setNonBlock(const bool yes)
00066 {
00067   if (fcntl(_socket, F_SETFL, yes ? O_NONBLOCK : ~O_NONBLOCK))
00068     return ERROR(MSG_SOCKET_CANNOT_SET_OPTION, strerror(errno));
00069 
00070   return OK;
00071 }
00072 
00073 TcpConnectionStatus TcpConnection::status() const
00074 {
00075   return _status;
00076 }
00077 
00078 // Private methods.
00079 
00080 int TcpConnection::setConnected()
00081 {
00082   _status = TCP_CONNECTION_STATUS_CONNECTED;
00083   EMIT(connected);
00084   return OK;
00085 }

Generated on Thu Sep 6 20:11:25 2007 for Pylon Application Platform by  doxygen 1.5.1