TraVisToClient.cpp 15.4 KB
Newer Older
1
/**
2 3
 * \file        travistoclient.cpp
 * \date        jul 4, 2014
4 5
 * \version     v0.7
 * \copyright   <2009-2015> Forschungszentrum Jülich GmbH. all rights reserved.
6
 *
7 8
 * \section license
 * this file is part of jupedsim.
9 10
 *
 * JuPedSim is free software: you can redistribute it and/or modify
11 12
 * it under the terms of the gnu lesser general public license as published by
 * the free software foundation, either version 3 of the license, or
13 14 15 16
 * any later version.
 *
 * JuPedSim is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
17 18
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. see the
 * gnu general public license for more details.
19
 *
Weichen's avatar
Weichen committed
20
 * You should have received a copy of the GNU Lesser General Public License
21
 * along with JuPedSim. if not, see <http://www.gnu.org/licenses/>.
22
 *
Weichen's avatar
Weichen committed
23
 * \section Description
24

25
 *
Weichen's avatar
Weichen committed
26
 **/
Ulrich Kemloh's avatar
Ulrich Kemloh committed
27 28 29 30 31 32 33 34 35


/********* include files ******************************************************/

#include <iostream>
#include <stdlib.h>
#include <string.h>
#include <stdio.h>
#include "TraVisToClient.h"
36
#include "../general/Macros.h"
Ulrich Kemloh's avatar
Ulrich Kemloh committed
37 38


39 40 41
//using namespace std;
using std::string;

Ulrich Kemloh's avatar
Ulrich Kemloh committed
42

43 44 45 46 47 48
TraVisToClient::TraVisToClient(string hostname, unsigned short port)
{
     _hostname=hostname;
     _port = port;
     _isConnected = false;
     createConnection();
Ulrich Kemloh's avatar
Ulrich Kemloh committed
49 50
}

51 52 53
TraVisToClient::~TraVisToClient()
{
     if (_isConnected) close();
Ulrich Kemloh's avatar
Ulrich Kemloh committed
54 55 56 57
}

/// send datablock to the server

58 59 60 61 62 63 64 65
void TraVisToClient::sendData(const char* data)
{
     // first create a new connection, in the case the last one was lost/close
     if (!_isConnected) {
          createConnection();
          //FIXME: queue messsage in a vector
          // msgQueue.push_back(data);
          return;
Ulrich Kemloh's avatar
Ulrich Kemloh committed
66

67 68 69 70
     }
     char msgSizeStr[10];
     int msgSize = (int)strlen(data);
     sprintf(msgSizeStr, "%d\n", msgSize);
Ulrich Kemloh's avatar
Ulrich Kemloh committed
71

72 73 74 75 76 77 78
     /* check if parameters are valid */
     if (NULL == data) {
          fprintf(stderr, "invalid message buffer!");
          fprintf(stderr, "leaving sendMessage()");
          _isConnected = false;
          return;
     }
Ulrich Kemloh's avatar
Ulrich Kemloh committed
79 80


81
     //  do until queue empty for()
Ulrich Kemloh's avatar
Ulrich Kemloh committed
82 83


84 85 86 87 88 89 90 91
     /*send the length of the message*/
     int msgsize = strlen(msgSizeStr);
     if (msgsize != send(_tcpSocket, (const char *) msgSizeStr, strlen(msgSizeStr), 0)) {
          fprintf(stderr, "sending message Size failed");
          fprintf(stderr, "leaving sendMessage()");
          _isConnected = false;
          return;
     }
Ulrich Kemloh's avatar
Ulrich Kemloh committed
92

93 94 95 96 97 98 99
     /* now send the message */
     if (msgSize != send(_tcpSocket, (const char *) data, msgSize, 0)) {
          fprintf(stderr, "sending message failed");
          fprintf(stderr, "leaving sendMessage()");
          _isConnected = false;
          return;
     }
Ulrich Kemloh's avatar
Ulrich Kemloh committed
100

101
     // end do
Ulrich Kemloh's avatar
Ulrich Kemloh committed
102 103 104 105
}

/// close the client (end the connection)

106 107 108 109 110 111 112 113 114 115 116 117 118 119
void TraVisToClient::close()
{
     if (_isConnected) {
          /* all things are done, so shutdown the connection */
          if (!shutdownAndCloseSocket(_tcpSocket)) {
               fprintf(stderr, "shutdown and close socket failed!");
               stopSocketSession();
               fprintf(stderr, "leaving main() with error");
               return;
          }

          /* stop the socket session */
          stopSocketSession();
     }
Ulrich Kemloh's avatar
Ulrich Kemloh committed
120 121 122

}

123 124 125 126 127
void TraVisToClient::createConnection()
{

     /* start the socket session */
     if (!startSocketSession()) {
Ulrich Kemloh's avatar
Ulrich Kemloh committed
128 129
          fprintf(stderr, "startSocketSession() failed!\n");
          fprintf(stderr, "socket creation failed for host [%s] on port [%d]!\n",_hostname.c_str(),_port);
130 131 132 133 134 135 136 137 138 139
          exit(EXIT_FAILURE);
     }

     /* create a new socket and connect the socket to the given service */
     if (INVALID_SOCKET == (_tcpSocket = createClientSocket(_hostname.c_str(), _port))) {
          fprintf(stderr, "\nsocket creation failed for host [%s] on port [%d]!\n",_hostname.c_str(),_port);
          stopSocketSession();
          exit(EXIT_FAILURE);
     }
     _isConnected = true;
Ulrich Kemloh's avatar
Ulrich Kemloh committed
140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155
}

/********* function definitions **************************************/

/**
 *  This function returns an integer (unsigned long) representation
 *  of an IP address, given as a FQN or a dotted IP address.
 *
 *  @param  hostName     name of a host as FQN or dotted IP address
 *
 *  @return  The return value is an integer value of a dotted IP address if
 *           the hostname exists (valid DNS entry) or the hostname is given
 *           as a dotted IP address. Otherwise the function returns
 *           @c INADDR_NONE.
 */
unsigned long
156 157 158 159
TraVisToClient::lookupHostAddress(const char *hostName)
{
     unsigned long addr; /* inet address of hostname */
     struct hostent *host; /* host structure for DNS request */
Ulrich Kemloh's avatar
Ulrich Kemloh committed
160

161
     dtrace("entering lookupHostAddress()");
Ulrich Kemloh's avatar
Ulrich Kemloh committed
162

163 164 165 166 167
     if (NULL == hostName) {
          derror("invalid parameter");
          dtrace("leaving lookupHostAddress()");
          return (INADDR_NONE);
     }
Ulrich Kemloh's avatar
Ulrich Kemloh committed
168

169
     dtrace("looking for host %s", hostName);
Ulrich Kemloh's avatar
Ulrich Kemloh committed
170

171
     addr = inet_addr(hostName);
Ulrich Kemloh's avatar
Ulrich Kemloh committed
172

173 174 175 176 177 178 179
     if (INADDR_NONE == addr) {
          /* hostName isn't a dotted IP, so resolve it through DNS */
          host = gethostbyname(hostName);
          if (NULL != host) {
               addr = *((unsigned long *) host->h_addr);
          }
     }
Ulrich Kemloh's avatar
Ulrich Kemloh committed
180

181 182
     dtrace("leaving lookupHostAddress()");
     return (addr);
Ulrich Kemloh's avatar
Ulrich Kemloh committed
183 184 185 186 187 188 189 190 191 192 193 194 195 196 197
}
/******** end of function lookupHostAddress **************************/

/**
 *  This function creates a new client internet domain socket (TCP/IP)
 *  and connects to a service on an internet host.
 *
 *  @param  serverName   hostname of a server
 *  @param  portNumber   port number of service
 *
 *  @return  The function returns a socket handle if the socket can be created
 *           and connected to a service. If an error occurred, the function
 *           returns @c INVALID_SOCKET.
 */
socket_t
198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238
TraVisToClient::createClientSocket(const char *serverName, unsigned short portNumber)
{
     unsigned long ipAddress; /* internet address */
     struct sockaddr_in srvAddr; /* server's internet socket address */
     socket_t sock; /* file descriptor for client socket */

     dtrace("entering createClientSocket()");

     /* get the IP address of the server host */
     if (INADDR_NONE == (ipAddress = lookupHostAddress(serverName))) {
          derror("lookupHostAddress() failed");
          dtrace("leaving createClientSocket() with INVALID_SOCKET");
          return (INVALID_SOCKET);
     }

     dtrace("trying to connect %s on port %hu", serverName, portNumber);

     /* create the client socket */
     if (INVALID_SOCKET == (sock = socket(AF_INET, SOCK_STREAM, IPPROTO_IP))) {
          derror("socket creation failed");
          dtrace("leaving createClientSocket() with INVALID_SOCKET");
          return (INVALID_SOCKET);
     }

     /* fill the server address structure */
     memset(&srvAddr, 0, sizeof (srvAddr));
     srvAddr.sin_family = AF_INET;
     srvAddr.sin_port = htons(portNumber);
     srvAddr.sin_addr.s_addr = ipAddress;

     /* try to connect to the server socket */
     if (SOCKET_ERROR == connect(sock, (struct sockaddr *) & srvAddr, sizeof (srvAddr))) {
          derror("connect() failed");
          //FIXME
          //closesocket(tcpSocket);
          dtrace("leaving createClientSocket() with INVALID_SOCKET");
          return (INVALID_SOCKET);
     }

     dtrace("leaving createClientSocket()");
     return (sock);
Ulrich Kemloh's avatar
Ulrich Kemloh committed
239 240 241 242 243 244 245 246 247 248 249 250
}
/******** end of function createClientSocket *************************/

/**
 *  This function creates a new server internet domain socket (TCP/IP).
 *
 *  @param  portNumber   port number on which to listen for incoming packets
 *
 *  @return  The function returns a socket handle if the socket can be created.
 *           If an error occurs, the function returns @c INVALID_SOCKET.
 */
socket_t
251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290
TraVisToClient::createServerSocket(unsigned short portNumber)
{
     struct sockaddr_in srvAddr; /* server's internet socket address */
     socket_t sock; /* file descriptor for server socket */

     dtrace("entering createServerSocket()");

     /* create the server socket */
     if (INVALID_SOCKET == (sock = socket(AF_INET, SOCK_STREAM, IPPROTO_IP))) {
          derror("socket creation failed");
          dtrace("leaving createServerSocket() with INVALID_SOCKET");
          return (INVALID_SOCKET);
     }

     /* fill the server address structure */
     /* first of all, zero srvAddr, so that we have a defined status */
     memset(&srvAddr, 0, sizeof (srvAddr));
     srvAddr.sin_family = AF_INET;
     srvAddr.sin_port = htons(portNumber);
     srvAddr.sin_addr.s_addr = htonl(INADDR_ANY);

     /* try to bind socket to the specified server port */
     if (SOCKET_ERROR == bind(sock, (struct sockaddr *) & srvAddr, sizeof (srvAddr))) {
          derror("bind() failed!");
          //FIXME:
          //closesocket(tcpSocket);
          dtrace("leaving createServerSocket() with INVALID_SOCKET");
          return (INVALID_SOCKET);
     }

     if (SOCKET_ERROR == listen(sock, QUEUE_LENGTH)) {
          derror("listen() failed!");
          shutdownAndCloseSocket(sock);
          dtrace("leaving createServerSocket() with INVALID_SOCKET");
          return (INVALID_SOCKET);
     }

     dtrace("server started at port %hu", portNumber);
     dtrace("leaving createServerSocket()");
     return (sock);
Ulrich Kemloh's avatar
Ulrich Kemloh committed
291 292 293 294 295 296 297 298 299 300 301 302 303 304 305
}
/******** end of function createServerSocket *************************/

/**
 *  This function sends a message of a given size to a communication
 *  partner via a connected socket.
 *
 *  @param  sock         socket for sending the message
 *  @param  msg          pointer to the message buffer which should be sent
 *  @param  msgSize      size of the message buffer
 *
 *  @return  The function returns @c true if the message was sent to the server,
 *           otherwise the function returns @c false.
 */
bool
306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333
TraVisToClient::sendMessage(socket_t sock, const void *msg, int msgSize)
{
     dtrace("entering sendMessage()");

     /* check if parameters are valid */
     if (NULL == msg) {
          derror("invalid message buffer!");
          dtrace("leaving sendMessage()");
          return (false);
     }

     if (0 >= msgSize) {
          derror("invalid message size %d", msgSize);
          dtrace("leaving sendMessage()");
          return (false);
     }

     dtrace("sending message of size %d", msgSize);

     /* now send the message */
     if (msgSize != send(sock, (const char *) msg, msgSize, 0)) {
          derror("sending message failed");
          dtrace("leaving sendMessage()");
          return (false);
     }

     dtrace("leaving sendMessage()");
     return (true);
Ulrich Kemloh's avatar
Ulrich Kemloh committed
334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350
}
/******** end of function sendMessage ********************************/

/**
 *  This functions receives a message from a communication partner and
 *  stores it into a given message buffer.
 *  The function blocks until all bytes have been successfully received,
 *  or an error occurred.
 *
 *  @param       sock       socket for receiving the message
 *  @param[out]  msg        message buffer for receiving the message
 *  @param       msgSize    size of the buffer to contain the message
 *
 *  @return  The function returns @c true if all things went well. Otherwise
 *           the function returns @c false.
 */
bool
351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402
TraVisToClient::receiveMessage(socket_t sock, void *msg, int msgSize)
{
     char *msgPart; /* pointer to the memory for receiving the message */
     int toReceive; /* number of bytes to receive */
     int received; /* number of bytes totally received */
     int nBytes; /* number of bytes currently received */

     dtrace("entering receiveMessage()");

     /* check if parameters are valid */
     if (NULL == msg) {
          derror("invalid message buffer!");
          dtrace("leaving receiveMessage()");
          return (false);
     }

     if (0 >= msgSize) {
          derror("invalid message size!");
          dtrace("leaving receiveMessage()");
          return (false);
     }

     msgPart = (char *) msg;
     received = 0;

     dtrace("trying to receive a message of size %d", msgSize);

     /* start receiving bytes from server until complete message is received */
     do {
          toReceive = msgSize - received;
          nBytes = recv(sock, msgPart, toReceive, 0);
          switch (nBytes) {
          case SOCKET_ERROR: /* error occurred */
               derror("error during message receipt");
               dtrace("leaving receiveMessage()");
               return (false);
          case 0: /* connection has been closed */
               derror("remote host has closed the connection");
               dtrace("leaving receiveMessage()");
               return (false);
          default: /* some bytes have been received */
               dtrace("received %d bytes of message", nBytes);
               received += nBytes;
               msgPart += nBytes;
               break;
          }
     } while (received != msgSize);

     dtrace("received message of size %d", received);

     dtrace("leaving receiveMessage()");
     return (true);
Ulrich Kemloh's avatar
Ulrich Kemloh committed
403 404 405 406 407 408 409 410 411 412 413 414
}
/******** end of function receiveMessage *****************************/

/**
 *  This function shuts down and closes a given socket.
 *
 *  @param  sock         socket to be closed
 *
 *  @return  if all things went ok, this function returns @c true, otherwise
 *           @c false
 */
bool
415 416 417
TraVisToClient::shutdownAndCloseSocket(socket_t sock)
{
     bool status = true;
Ulrich Kemloh's avatar
Ulrich Kemloh committed
418

419
     dtrace("entering shutdownAndCloseSocket()");
Ulrich Kemloh's avatar
Ulrich Kemloh committed
420

421 422 423 424
     if (SOCKET_ERROR == shutdown(sock, SHUT_RDWR)) {
          derror("shutdown() failed");
          status = false;
     }
Ulrich Kemloh's avatar
Ulrich Kemloh committed
425

426 427 428 429 430
     //FIXME:
     //if (SOCKET_ERROR == closesocket(tcpSocket)) {
     //  derror("closesocket() failed");
     //  status = false;
     //}
Ulrich Kemloh's avatar
Ulrich Kemloh committed
431

432 433
     dtrace("leaving shutdownAndCloseSocket()");
     return (status);
Ulrich Kemloh's avatar
Ulrich Kemloh committed
434 435 436 437 438
}

/******** end of function shutdownAndCloseSocket *********************/

void
439 440
TraVisToClient::_printErrorMessage(void)
{
Ulrich Kemloh's avatar
Ulrich Kemloh committed
441 442 443 444 445 446 447 448 449 450 451 452
}


#ifdef _WIN32

/**
 *  This function initializes the Win32 Socket API.
 *
 *  @return  if all things went ok, this function returns @c true, otherwise
 *           @c false
 */
bool
453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485
TraVisToClient::_startWin32SocketSession(void)
{
     WORD requestedVersion;
     WSADATA wsaData;

     dtrace("entering _startWin32SocketSession()");

     requestedVersion = MAKEWORD(WS_MAJOR_VERSION, WS_MINOR_VERSION);

     if (0 != WSAStartup(requestedVersion, &wsaData)) {
          derror("WSAStartup() failed");
          dtrace("leaving _startWin32SocketSession() with error");
          return (false);
     }

     /* Confirm that the Windows Socket DLL supports 1.1. */
     /* Note that if the DLL supports versions greater    */
     /* than 1.1 in addition to 1.1, it will still return */
     /* 1.1 in wVersion since that is the version we      */
     /* requested.                                        */

     if (WS_MINOR_VERSION != LOBYTE(wsaData.wVersion)
               || WS_MAJOR_VERSION != HIBYTE(wsaData.wVersion)) {
          derror("Windows Socket DLL does not support the requested version");
          _stopWin32SocketSession();
          dtrace("leaving _startWin32SocketSession() with error");
          return (false);
     }

     WSASetLastError(0); /* reset the error code */

     dtrace("leaving _startWin32SocketSession()");
     return (true);
Ulrich Kemloh's avatar
Ulrich Kemloh committed
486 487 488 489 490 491 492 493
}
/******** end of function _startWin32SocketSession *******************/

/**
 *  This function terminates the Win32 Socket API.
 *  No future API calls are allowed.
 */
void
494 495 496
TraVisToClient::_stopWin32SocketSession(void)
{
     dtrace("entering _stopWin32SocketSession()");
Ulrich Kemloh's avatar
Ulrich Kemloh committed
497

498 499 500
     if (SOCKET_ERROR == WSACleanup()) {
          derror("WSACleanup() failed");
     }
Ulrich Kemloh's avatar
Ulrich Kemloh committed
501

502 503
     dtrace("leaving _stopWin32SocketSession()");
     return;
Ulrich Kemloh's avatar
Ulrich Kemloh committed
504 505 506 507 508
}
/******** end of function _stopWin32SocketSession ********************/

#endif /* _WIN32 */