CSIS 440 chat client/server project.

User.cpp 2.8KB

    /* Author: Matt Kava Asmt: CSIS 440, Spring 2010, Assignment 6 :: IRC-Like Client/Server Description: Sirc User class implementation - Handles interaction with users */ #include "User.h" #include "constants.h" #include <sys/types.h> // For data types #include <sys/socket.h> // For socket(), connect(), send(), and recv() #include <netdb.h> // For gethostbyname() #include <arpa/inet.h> // For inet_addr() #include <unistd.h> // For close() #include <netinet/in.h> // For sockaddr_in #include <stdio.h> // For sprintf using namespace std; /** Constructors, Deconstructors, etc ... **/ User::User() { _nick = ""; _sockfd = -1; _ip = "ip"; _port = "port"; _validated = false; } User::User(string nick, int sockfd) { _nick = nick; _sockfd = sockfd; _ip = "ip"; _port = "port"; _validated = false; } User::~User() { CloseSocket(); } /** END Constructors **/ /** Methods for dealing with Private data members **/ string User::Nick() { return _nick; } void User::Nick(string nick) { _nick = nick; } string User::IP() { return _ip; } void User::IP(string ip) { _ip = ip; } string User::Port() { return _port; } void User::Port(string port) { _port = port; } int User::SockFD() { return _sockfd; } void User::SockFD(int sock) { _sockfd = sock; } bool User::Validated() { return _validated; } void User::Validated(bool b) { _validated = b; } /** END Private data member methods **/ void User::CloseSocket() { // if its a valid socket... if(_sockfd > -1) { // close it close(_sockfd); } } void User::Send(string message) { if(_sockfd < 0) return; int read_val; // send the message read_val = send(_sockfd, message.c_str(), message.size(), 0); } string User::Recv() { if(_sockfd < 0) return ""; string msg = ""; char buffer[BUFFER_SIZE]; int read_val = 0; // get the message the server sent into a buffer read_val = recv(_sockfd, buffer, BUFFER_SIZE, 0); // gather the message // only read up to a newline or as many bytes as // we think are there for(int i = 0; buffer[i] != '\n' && i < read_val; i++) { msg = msg + buffer[i]; } return msg; } bool User::LoadIpPort() { // if the socketfd is invalid, don't try to load the IP and Port... just return if(_sockfd < 0) return false; // get the address from the socket sockaddr_in addr; unsigned int addr_len = sizeof(addr); // get the address information from the socket if (getpeername(_sockfd, (sockaddr *) &addr, (socklen_t *) &addr_len) < 0) { // error return false; } // convert the port number into a useable format... like a string char port[6]; sprintf(port,"%d", ntohs(addr.sin_port) ); // convert the IP to a string and assign it IP( inet_ntoa(addr.sin_addr) ); // assign the port number Port( port ); // no problem, IP and Port are loaded return true; }