No Description
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

TcpServer.cpp 2.4KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293
  1. /*******************************************************************************
  2. * Copyright (c) 2018 INSA - GEI, Toulouse, France.
  3. * All rights reserved. This program and the accompanying materials
  4. * are made available "AS IS", without any warranty of any kind.
  5. *
  6. * INSA assumes no responsibility for errors or omissions in the
  7. * software or documentation available.
  8. *
  9. * Part of code Copyright ST Microelectronics.
  10. *
  11. * Contributors:
  12. * Lucien Senaneuch - Initial API and implementation
  13. * Sebastien DI MERCURIO - Maintainer since Octobre 2018
  14. *******************************************************************************/
  15. #include "TcpServer.h"
  16. #include <netinet/in.h>
  17. #include <zconf.h>
  18. #include <vector>
  19. TcpServer::TcpServer() {
  20. this->socketFD = -1;
  21. this->socketClients.clear();
  22. }
  23. int TcpServer::Listen (int port) {
  24. struct sockaddr_in server;
  25. this->socketFD = socket(AF_INET, SOCK_STREAM, 0);
  26. if(this->socketFD < 0){
  27. throw invalid_argument("Can not create socket");
  28. }
  29. server.sin_addr.s_addr = INADDR_ANY;
  30. server.sin_family = AF_INET;
  31. server.sin_port = htons(port);
  32. if(bind(this->socketFD, (struct sockaddr *) &server, sizeof(server)) < 0) {
  33. throw invalid_argument("Can not bind socket");
  34. }
  35. listen(this->socketFD , NB_CONNECTION_MAX);
  36. return this->socketFD;
  37. }
  38. int TcpServer::AcceptClient() {
  39. struct sockaddr_in client;
  40. int c = sizeof(struct sockaddr_in);
  41. int fd = accept(this->socketFD,(struct sockaddr *) &client, (socklen_t*)&c);
  42. if (fd >=0 )
  43. this->socketClients.push_back(fd);
  44. else throw invalid_argument("Accept failed in TcpServer::AcceptClient");
  45. return fd;
  46. }
  47. int TcpServer::Send(int client, string mes) {
  48. return write(client, mes.c_str(), mes.size());
  49. }
  50. string TcpServer::Receive(int client_fd, int size){
  51. char tab[size];
  52. if(recv(client_fd,tab,size,0) >0) {
  53. tab[size] = 0;
  54. return string(tab);
  55. } else
  56. return string();
  57. }
  58. int TcpServer::Broadcast(string mes) {
  59. for (int socket : this->socketClients) {
  60. int err = write(socket, mes.c_str(), mes.size());
  61. }
  62. return 0;
  63. }
  64. const vector<int> &TcpServer::getSocketClients() const {
  65. return socketClients;
  66. }
  67. void TcpServer::SetSocketClients(const std::vector<int> &socketClients) {
  68. this->socketClients = socketClients;
  69. }
  70. TcpServer::~TcpServer() {
  71. close(this->socketFD);
  72. }