Project::OSiRiON - Git repositories
Project::OSiRiON
News . About . Screenshots . Downloads . Forum . Wiki . Tracker . Git
summaryrefslogtreecommitdiff
blob: c148e908fd3a9311a814384627347c7ecfed7dc1 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
/*
   net/tcpclient.cc
   This file is part of the Osirion project and is distributed under
   the terms of the GNU General Public License version 2
*/

#include <sys/types.h>
#include <sys/socket.h>
#include <assert.h>

#include <iostream>

#include "sys/sys.h"
#include "net/net.h"
#include "net/tcpclient.h"

namespace net
{

TCPClient::TCPClient(int tcpclientfd)
{
	tcpclient_fd = tcpclientfd;
	tcpclient_error = false;
}

TCPClient::~TCPClient()
{
	if (tcpclient_fd != -1) {
		client_disconnect();
		close(tcpclient_fd);
	}
}

bool TCPClient::error() const
{
	return tcpclient_error;
}

bool TCPClient::valid() const
{
	return (tcpclient_fd != -1);
}

bool TCPClient::invalid() const
{
	return (tcpclient_fd == -1);
}

int TCPClient::fd() const
{
	return (tcpclient_fd);
}
void TCPClient::abort()
{
	tcpclient_error= true;
}

void TCPClient::receive(std::string &msg)
{
	if (error() || invalid())
		return;
		
	char		recvbuf[FRAMESIZE]; // maximum block sizeq
	size_t		msglen = sizeof(recvbuf);
	ssize_t		bytes_received;
	
	memset(recvbuf, '\0', sizeof(recvbuf));
	bytes_received = ::recv(tcpclient_fd, recvbuf, msglen, 0);
	if (bytes_received == 0) {
		//con_print << "Client " << fd() << " disconnected." << std::endl;
		client_disconnect();
		abort();
		return;
	} else if (bytes_received < 0) {
		//con_warn << "Client " << fd() << " receive() error!" << std::endl;
		// FIXME redirect error message
		perror("recv");		
		abort();
		client_disconnect();
		return;
	}
	msg = recvbuf;
}

void TCPClient::send(std::string const &msg)
{
	if (error() || invalid())
		return;
		
	if (msg.size() > FRAMESIZE) {
		con_warn << "Network message exceeds " << FRAMESIZE << " bytes!" << std::endl;
		return;
	}
	
	ssize_t 	bytes_sent = 0;
	size_t		total_sent = 0;
	std::string	sendbuf(msg);
	
	while (total_sent <  msg.size()) {
		bytes_sent = ::send(tcpclient_fd, sendbuf.c_str(), sendbuf.size(), 0);
		if (bytes_sent < 0) {
			con_warn << "Client " << fd() << " send() error!" << std::endl;
			// FIXME redirect error message
			perror("send");
			abort();
			client_disconnect();
			return;
		}
		total_sent += bytes_sent;
		
		sendbuf.erase(sendbuf.size() - bytes_sent, bytes_sent);
	}
	
	return;
}

void TCPClient::client_disconnect()
{
	/* error() indicates if it was a clean disconnect or not */
}

}