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.

72 lines
1.9 KiB

3 years ago
  1. #include "SocketClient.h"
  2. #include <stdio.h>
  3. #include <string.h>
  4. #include <unistd.h>
  5. using namespace std;
  6. namespace exploringBB {
  7. SocketClient::SocketClient(std::string serverName, int portNumber) {
  8. this->socketfd = -1;
  9. this->server = NULL;
  10. this->serverName = serverName;
  11. this->portNumber = portNumber;
  12. this->isConnected = false;
  13. }
  14. int SocketClient::connectToServer(){
  15. socketfd = socket(AF_INET, SOCK_STREAM, 0);
  16. if (socketfd < 0){
  17. perror("Socket Client: error opening socket.\n");
  18. return 1;
  19. }
  20. server = gethostbyname(serverName.data());
  21. if (server == NULL) {
  22. perror("Socket Client: error - no such host.\n");
  23. return 1;
  24. }
  25. bzero((char *) &serverAddress, sizeof(serverAddress));
  26. serverAddress.sin_family = AF_INET;
  27. bcopy((char *)server->h_addr,(char *)&serverAddress.sin_addr.s_addr, server->h_length);
  28. serverAddress.sin_port = htons(portNumber);
  29. if (connect(socketfd, (struct sockaddr *) &serverAddress, sizeof(serverAddress)) < 0){
  30. perror("Socket Client: error connecting to the server.\n");
  31. return 1;
  32. }
  33. this->isConnected = true;
  34. return 0;
  35. }
  36. int SocketClient::send(std::string message){
  37. const char *writeBuffer = message.data();
  38. int length = message.length();
  39. int n = write(this->socketfd, writeBuffer, length);
  40. if (n < 0){
  41. perror("Socket Client: error writing to socket");
  42. return 1;
  43. }
  44. return 0;
  45. }
  46. string SocketClient::receive(int size=1024){
  47. char readBuffer[size];
  48. int n = read(this->socketfd, readBuffer, sizeof(readBuffer));
  49. if (n < 0){
  50. perror("Socket Client: error reading from socket");
  51. }
  52. return string(readBuffer);
  53. }
  54. int SocketClient::disconnectFromServer(){
  55. this->isConnected = false;
  56. close(this->socketfd);
  57. return 0;
  58. }
  59. SocketClient::~SocketClient() {
  60. if (this->isConnected == true){
  61. disconnectFromServer();
  62. }
  63. }
  64. }