client.cpp 1.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. #include "client.hpp"
  2. Client::Client(string server_ip,int server_port){
  3. socket_fd=socket(AF_INET, SOCK_STREAM, 0);
  4. if(socket_fd<0){
  5. cerr<<"[Error] I can't open socket"<<endl;
  6. exit(-1);
  7. }
  8. sockaddr_in serv_addr;
  9. bzero((char *) &serv_addr, sizeof(serv_addr));
  10. serv_addr.sin_family = AF_INET;
  11. serv_addr.sin_addr.s_addr = inet_addr(server_ip.c_str());
  12. serv_addr.sin_port = htons(server_port);
  13. if(connect(socket_fd,(struct sockaddr *) &serv_addr,sizeof(serv_addr))<0){
  14. cerr<<"[Error] I can't connect socket"<<endl;
  15. cout<<errno<<endl;
  16. exit(-1);
  17. }
  18. has_message=false;
  19. }
  20. void Client::listen(){
  21. char buffer;
  22. int l=recv(socket_fd,&buffer,1,MSG_PEEK);
  23. if(l>0){
  24. get_message();
  25. }
  26. if(l==0){
  27. cerr<<"[Error] Server was done"<<endl;
  28. exit(-1);
  29. }
  30. }
  31. void
  32. Client::get_message(){
  33. char buffer;
  34. message.clear();
  35. do{
  36. recv(socket_fd,&buffer,1,0);
  37. }while(message.add(buffer));
  38. has_message=true;
  39. }
  40. void
  41. Client::send_string(string str){
  42. size_t offset=0;
  43. Message msg;
  44. while(offset<str.size()){
  45. size_t len=min((size_t)(MAX_MSG_SIZE-3),str.size()-offset);
  46. msg.set_string(str.substr(offset,len));
  47. send_message(msg);
  48. offset+=len;
  49. }
  50. }