Advertisement
Guest User

Untitled

a guest
Mar 30th, 2013
172
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.74 KB | None | 0 0
  1. #include <iostream>
  2. /* A simple server in the internet domain using TCP
  3.    The port number is passed as an argument */
  4. #include <stdio.h>
  5. #include <stdlib.h>
  6. #include <string.h>
  7. #include <unistd.h>
  8. #include <sys/types.h>
  9. #include <sys/socket.h>
  10. #include <netinet/in.h>
  11.  
  12. enum
  13. {
  14.     CON_PORT = 9235
  15. };
  16.  
  17. void error(const char *msg)
  18. {
  19.     perror(msg);
  20.     exit(1);
  21. }
  22.  
  23. int main ()
  24. {
  25.     int sockfd, newsockfd, portno;
  26.          socklen_t clilen;
  27.          char buffer[256];
  28.          struct sockaddr_in serv_addr, cli_addr;
  29.          int n;
  30.  
  31.  
  32.          sockfd = socket(AF_INET, SOCK_STREAM, 0);
  33.          if (sockfd < 0)
  34.             error("ERROR opening socket");
  35.  
  36.          bzero((char *) &serv_addr, sizeof(serv_addr));
  37.  
  38.          portno = CON_PORT;
  39.          serv_addr.sin_family = AF_INET;
  40.          serv_addr.sin_addr.s_addr = INADDR_ANY;
  41.          serv_addr.sin_port = htons(portno);
  42.          if (bind(sockfd, (struct sockaddr *) &serv_addr,
  43.                   sizeof(serv_addr)) < 0)
  44.                   error("ERROR on binding");
  45.          std::cout << "Waiting for client\n";
  46.          listen(sockfd,5);
  47.          clilen = sizeof(cli_addr);
  48.  
  49.          newsockfd = accept(sockfd,
  50.                      (struct sockaddr *) &cli_addr,
  51.                      &clilen);
  52.          if (newsockfd < 0)
  53.               error("ERROR on accept");
  54.          bzero(buffer,256);
  55.          n = read(newsockfd,buffer,255);
  56.          if (n < 0) error("ERROR reading from socket");
  57.          printf("Here is the message: %s\n",buffer);
  58.  
  59.          std::string outStr = "";
  60.  
  61.          do
  62.          {
  63.              std::cout << "Please enter chat";
  64.              std::cin >> outStr;
  65.  
  66.              n = write(newsockfd,outStr.c_str(),18);
  67.              if (n < 0) error("ERROR writing to socket");
  68.          }while(outStr != "exit");
  69.          close(newsockfd);
  70.          close(sockfd);
  71.          return 0;
  72. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement