1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95
|
// serversocket.cpp: implementation of the ServerSocket class.
//
//////////////////////////////////////////////////////////////////////
#include "serversocket.h"
//////////////////////////////////////////////////////////////////////
// Construction/Destruction
//////////////////////////////////////////////////////////////////////
ServerSocket::ServerSocket()
{
connected = false;
}
bool ServerSocket::init()
{
struct sockaddr_in inet_address;
inet_address.sin_family = AF_INET;
inet_address.sin_port = htons(1234);
unsigned int inaddr_any = INADDR_ANY;
WORD wVersion;
WSADATA wsaData;
int lo, hi;
int min = 1, maj = 1;
wVersion = MAKEWORD(maj, min);
int err = WSAStartup(wVersion, &wsaData);
if (err != 0) {
MessageBox(NULL, L"Invalid WSAStartupcall", L"Snap", MB_OK);
return false;
}
lo = LOBYTE(wsaData.wVersion);
hi = HIBYTE(wsaData.wVersion);
if ((lo != maj) || (hi != min)) {
WSACleanup();
MessageBox(NULL, L"Winsock-Version not supported", L"Snap", MB_OK);
return false;
}
s = socket(AF_INET, SOCK_STREAM, 0);
if (s == INVALID_SOCKET) {
MessageBox(NULL, L"Could not create ServerSocket", L"Snap", MB_OK);
return false;
}
memcpy(&inet_address.sin_addr, &inaddr_any, sizeof(INADDR_ANY));
if (bind(s, (const sockaddr *) &inet_address,
sizeof(struct sockaddr_in)) == SOCKET_ERROR) {
MessageBox(NULL, L"Could not bind ServerSocket", L"Snap",
MB_OK | MB_ICONERROR);
return false;
}
if (listen(s, 5) == SOCKET_ERROR) {
MessageBox(NULL, L"Could not listen on ServerSocket", L"Snap",
MB_OK | MB_ICONERROR);
return false;
}
return true;
}
SOCKET ServerSocket::acceptClient()
{
cs = accept(s, NULL, NULL);
if (cs == INVALID_SOCKET) {
MessageBox(NULL, L"Could not accept on ServerSocket", L"Snap",
MB_OK | MB_ICONERROR);
}
connected = true;
return cs;
}
ServerSocket::~ServerSocket()
{
closesocket(s);
if (connected) {
shutdown(cs, 2);
closesocket(cs);
}
}
|