Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #define DEFAULT_PORT "27015"
- #ifndef _WIN32_WINNT
- #define _WIN32_WINNT 0x501 //For getaddr function
- #endif
- #ifndef WIN32_LEAN_AND_MEAN
- #define WIN32_LEAN_AND_MEAN
- #endif
- #include <cstring>
- #include <winsock2.h>
- #include <ws2tcpip.h>
- #include <iphlpapi.h>
- #include <windows.h>
- #include <windowsx.h>
- #include <tchar.h>
- #include "ServerClass.h"
- /*SOCKET ListenSocket = INVALID_SOCKET;
- SOCKET ClientSocket = INVALID_SOCKET;
- char recvbufx[DEFAULT_BUFLEN];
- int recvbuflen;*/
- int ServerClass::CreateServer(HWND hwindz)
- {
- struct addrinfo *result = NULL, *ptr = NULL, hints;
- //int iResult, iSendResult;
- //int recvbuflen = DEFAULT_BUFLEN;
- WSADATA wsaData;
- if(WSAStartup(MAKEWORD(2,2), &wsaData) != 0)
- {
- MessageBox(hwindz, "Network error: Could not initialize socket library!", "Error", MB_OK | MB_ICONERROR);
- return 1;
- }
- ZeroMemory(&hints, sizeof (hints));
- hints.ai_family = AF_INET;
- hints.ai_socktype = SOCK_STREAM;
- hints.ai_protocol = IPPROTO_TCP;
- hints.ai_flags = AI_PASSIVE;
- // Resolve the local address and port to be used by the server
- if (getaddrinfo(NULL, DEFAULT_PORT, &hints, &result) != 0) {
- MessageBox(hwindz, "Network error: Could not resolve the server address!", "Error", MB_OK | MB_ICONERROR);
- WSACleanup();
- return 1;
- }
- // Create a SOCKET for the server to listen for client connections
- ListenSocket = socket(result->ai_family, result->ai_socktype, result->ai_protocol);
- if (ListenSocket == INVALID_SOCKET) {
- MessageBox(hwindz, "Error creating socket!", "Error", MB_OK | MB_ICONERROR);
- //WSAGetLastError()
- freeaddrinfo(result);
- WSACleanup();
- return 1;
- }
- // Setup the TCP listening socket
- if (bind( ListenSocket, result->ai_addr, (int)result->ai_addrlen) == SOCKET_ERROR) {
- MessageBox(hwindz, "Could not bind the socket!", "Error", MB_OK | MB_ICONERROR);
- freeaddrinfo(result);
- closesocket(ListenSocket);
- WSACleanup();
- return 1;
- }
- freeaddrinfo(result);
- if ( listen( ListenSocket, SOMAXCONN ) == SOCKET_ERROR ) {
- MessageBox(hwindz, "Could not listen to the socket!", "Error", MB_OK | MB_ICONERROR);
- closesocket(ListenSocket);
- WSACleanup();
- return 1;
- }
- ClientSocket = INVALID_SOCKET;
- ClientSocket = accept(ListenSocket, NULL, NULL);
- if (ClientSocket == INVALID_SOCKET) {
- MessageBox(hwindz, "Refuses to connect!", "Error", MB_OK | MB_ICONERROR);
- closesocket(ListenSocket);
- WSACleanup();
- return 1;
- }
- return 0;
- }
- int ServerClass::CloseServer()
- {
- closesocket(ClientSocket);
- WSACleanup();
- return 0;
- }
- char* ServerClass::getcbuffer()
- {
- return recvbufx;
- }
- static int ServerClass::listensock()
- {
- if(recv(ClientSocket, recvbufx, recvbuflen, 0) > 0)
- {
- return recvbuflen;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement