Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <string>
- #include <iostream>
- #include <cstdio>
- #include <cstdlib>
- #include <cstring>
- #include <sys/types.h>
- #include <sys/socket.h>
- #include <netdb.h>
- #include <unistd.h>
- #include <sys/time.h>
- #include <sys/wait.h>
- #include <signal.h>
- #include <sys/poll.h>
- class Socket
- {
- public:
- Socket(std::string port)
- {
- prepareAddrinfo(port);
- sockfd = socket(res->ai_family, res->ai_socktype, res->ai_protocol);
- if (sockfd == -1)
- {
- perror("socket");
- exit(1);
- }
- else
- {
- printf("Created socket\n");
- }
- if (setNonBlocking() < 0)
- {
- perror("socket");
- }
- else
- {
- printf("Set socket to non-blocking mode\n");
- }
- }
- Socket(int sock)
- {
- if (sock < 0)
- {
- perror("socket");
- exit(1);
- }
- sockfd = sock;
- }
- ~Socket()
- {
- close(sockfd);
- }
- void prepareAddrinfo(std::string port)
- {
- memset(&hints, 0, sizeof hints);
- hints.ai_family = AF_UNSPEC;
- hints.ai_socktype = SOCK_STREAM;
- hints.ai_flags = AI_PASSIVE;
- getaddrinfo(NULL, port.c_str(), &hints, &res);
- }
- int getSocket()
- {
- return sockfd;
- }
- int Bind()
- {
- return bind(sockfd, res->ai_addr, res->ai_addrlen);
- }
- int Listen(int connections = 1)
- {
- return listen(sockfd, connections);
- }
- int Accept()
- {
- return accept(sockfd, NULL, NULL);
- }
- int Send(std::string data)
- {
- return send(sockfd, data.c_str(), data.length(), 0);
- }
- std::string Recv(int block = 1024)
- {
- char *buffer;
- buffer = new char[block];
- memset(buffer, 0, block);
- recv(sockfd, buffer, block, 0);
- std::string msg = buffer;
- delete buffer;
- return msg;
- }
- int setNonBlocking()
- {
- return setsockopt(sockfd, SOL_SOCKET, SO_REUSEADDR, (char *)&blocking,
- sizeof(blocking));
- }
- private:
- int sockfd, blocking;
- struct addrinfo hints, *res;
- };
- class Server
- {
- public:
- Server()
- {
- printf("Starting server\n");
- srvSock = new Socket("8080");
- srvSock->Bind();
- srvSock->Listen();
- this->mainLoop();
- }
- ~Server()
- {
- delete srvSock;
- printf("Cleaned up\n");
- }
- virtual int mainLoop() = 0;
- protected:
- Socket * srvSock;
- };
- class ChatServer:public Server
- {
- public:
- int mainLoop()
- {
- return 0;
- }
- };
- int main()
- {
- ChatServer *s;
- s = new ChatServer();
- delete s;
- printf("Bye :)\n");
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement