Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include "Communicator.h"
- #include <thread>
- #include <iostream>
- #include <exception>
- #include <string>
- #define PORT 4242
- Communicator::Communicator(RequestHandlerFactory* handlerFactory) : m_handlerFactory(handlerFactory)
- {
- // notice that we step out to the global namespace
- // for the resolution of the function socket
- // this server use TCP. that why SOCK_STREAM & IPPROTO_TCP
- // if the server use UDP we will use: SOCK_DGRAM & IPPROTO_UDP
- m_socket = ::socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
- if (m_socket == INVALID_SOCKET)
- throw std::exception(__FUNCTION__ " - socket");
- }
- Communicator::~Communicator()
- {
- try
- {
- // the only use of the destructor should be for freeing
- // resources that was allocated in the constructor
- ::closesocket(m_socket);
- }
- catch (...) {}
- }
- void Communicator::bindAndListen()
- {
- struct sockaddr_in sa = { 0 };
- sa.sin_port = htons(PORT); // port that server will listen for
- sa.sin_family = AF_INET; // must be AF_INET
- sa.sin_addr.s_addr = INADDR_ANY; // when there are few ip's for the machine. We will use always "INADDR_ANY"
- // again stepping out to the global namespace
- // Connects between the socket and the configuration (port and etc..)
- if (::bind(m_socket, (struct sockaddr*)&sa, sizeof(sa)) == SOCKET_ERROR)
- throw std::exception(__FUNCTION__ " - bind");
- // Start listening for incoming requests of clients
- if (::listen(m_socket, SOMAXCONN) == SOCKET_ERROR)
- throw std::exception(__FUNCTION__ " - listen");
- std::cout << "Listening on port " << PORT << std::endl;
- while (true)
- {
- // the main thread is only accepting clients
- // and add then to the list of handlers
- std::cout << "Waiting for client connection request" << std::endl;
- // this accepts the client and create a specific socket from server to this client
- SOCKET client_socket = ::accept(m_socket, NULL, NULL);
- if (client_socket == INVALID_SOCKET)
- throw std::exception(__FUNCTION__);
- std::cout << "Client accepted. Server and client can speak" << std::endl;
- // the function that handle the conversation with the client
- std::thread t(&Communicator::startThreadForNewClient, this, client_socket);
- }
- }
- void Communicator::handleRequests()
- {
- }
- void Communicator::startThreadForNewClient(SOCKET socket)
- {
- try
- {
- std::string s = "Welcome! What is your name (4 bytes)? ";
- send(socket, s.c_str(), s.size(), 0); // last parameter: flag. for us will be 0.
- char m[5];
- recv(socket, m, 4, 0);
- m[4] = 0;
- std::cout << "Client name is: " << m << std::endl;
- s = "Bye";
- send(socket, s.c_str(), s.size(), 0);
- // Closing the socket (in the level of the TCP protocol)
- closesocket(socket);
- }
- catch (const std::exception& e)
- {
- closesocket(socket);
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement