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.

server.cpp 2.0KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899
  1. /*
  2. * To change this license header, choose License Headers in Project Properties.
  3. * To change this template file, choose Tools | Templates
  4. * and open the template in the editor.
  5. */
  6. /*
  7. * File: server.cpp
  8. * Author: dimercur
  9. *
  10. * Created on 19 octobre 2018, 14:24
  11. */
  12. #include "server.h"
  13. #include <sys/socket.h>
  14. #include <arpa/inet.h>
  15. #include <netinet/in.h>
  16. #include <stdio.h>
  17. #include <stdlib.h>
  18. #include <unistd.h>
  19. #define NB_CONNECTION_MAX 1
  20. int socketFD = -1;
  21. int clientID = -1;
  22. int openServer(int port) {
  23. struct sockaddr_in server;
  24. socketFD = socket(AF_INET, SOCK_STREAM, 0);
  25. if (socketFD < 0) {
  26. perror("Can not create socket");
  27. exit(-1);
  28. }
  29. server.sin_addr.s_addr = INADDR_ANY;
  30. server.sin_family = AF_INET;
  31. server.sin_port = htons(port);
  32. if (bind(socketFD, (struct sockaddr *) &server, sizeof (server)) < 0) {
  33. perror("Can not bind socket");
  34. exit(-1);
  35. }
  36. listen(socketFD, NB_CONNECTION_MAX);
  37. return socketFD;
  38. }
  39. int closeServer() {
  40. close(socketFD);
  41. socketFD = -1;
  42. return 0;
  43. }
  44. int acceptClient() {
  45. struct sockaddr_in client;
  46. int c = sizeof (struct sockaddr_in);
  47. clientID = accept(socketFD, (struct sockaddr *) &client, (socklen_t*) & c);
  48. if (clientID < 0) {
  49. perror("Accept failed in acceptClient");
  50. exit(-1);
  51. }
  52. return clientID;
  53. }
  54. int sendDataToServer(char *data, int length) {
  55. return sendDataToServerForClient(clientID, data, length);
  56. }
  57. int sendDataToServerForClient(int client, char *data, int length) {
  58. if (client >= 0)
  59. return write(client, (void*)data, length);
  60. else return 0;
  61. }
  62. int receiveDataFromServer(char *data, int size) {
  63. return receiveDataFromServerFromClient(clientID, data, size);
  64. }
  65. int receiveDataFromServerFromClient(int client, char *data, int size) {
  66. char length = 0;
  67. if (client > 0) {
  68. if ((length = recv(client, (void*)data, size, 0)) > 0) {
  69. data[length] = 0;
  70. }
  71. }
  72. return length;
  73. }