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 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112
|
#include "Server.hpp"
using namespace std;
//Constructor declaration.
Server::Server():
receivebuffer(512),
recvbuflen(512),
listensocket(INVALID_SOCKET),
clientsocket(INVALID_SOCKET)
{
wVersionRequested = MAKEWORD(2, 0);
// Initialize Winsock
iResult = WSAStartup(MAKEWORD(2, 2), &wsaData);
if (iResult != 0) {
printf("WSAStartup failed with error: %d\n", iResult);
}
peer.sin_family = AF_INET;
peer.sin_port = htons(9171); // port 9171
peer.sin_addr.S_un.S_addr = htonl(INADDR_ANY);
// Create a SOCKET for connecting to server
listensocket = socket(peer.sin_family, SOCK_STREAM, 0);
if (listensocket == INVALID_SOCKET) {
printf("socket failed with error: %ld\n", WSAGetLastError());
WSACleanup();
}
// Setup the TCP listening socket
iResult = bind(listensocket, (sockaddr *)&peer, sizeof(peer));
if (iResult == SOCKET_ERROR) {
printf("bind failed with error: %d\n", WSAGetLastError());
closesocket(listensocket);
WSACleanup();
}
iResult = listen(listensocket, SOMAXCONN);
if (iResult == SOCKET_ERROR) {
printf("listen failed with error: %d\n", WSAGetLastError());
closesocket(listensocket);
WSACleanup();
}
// Accept a client socket
clientsocket = accept(listensocket, NULL, NULL);
if (clientsocket == INVALID_SOCKET) {
printf("accept failed with error: %d\n", WSAGetLastError());
closesocket(listensocket);
WSACleanup();
}
closesocket(listensocket);
iResult = recv(clientsocket, &receivebuffer, recvbuflen, 0);
if (iResult > 0)
{
printf("Bytes received: %d\n", iResult);
}
// Delay
cout << "Waiting..." << endl; char ch; cin >> ch;
// Cleanup windows sockets
WSACleanup();
}
Server::~Server()
{
}
void Server::update()
{
// Receive until the peer shuts down the connection
do {
iResult = recv(clientsocket, &receivebuffer, recvbuflen, 0);
if (iResult > 0) {
printf("Bytes received: %d\n", iResult);
// Echo the buffer back to the sender
iSendResult = send(clientsocket, &receivebuffer, iResult, 0);
if (iSendResult == SOCKET_ERROR) {
printf("send failed with error: %d\n", WSAGetLastError());
closesocket(clientsocket);
WSACleanup();
}
printf("Bytes sent: %d\n", iSendResult);
}
else if (iResult == 0)
printf("Connection closing...\n");
else {
printf("recv failed with error: %d\n", WSAGetLastError());
closesocket(clientsocket);
WSACleanup();
}
} while (iResult > 0);
// shutdown the connection since we're done
iResult = shutdown(clientsocket, SD_SEND);
if (iResult == SOCKET_ERROR) {
printf("shutdown failed with error: %d\n", WSAGetLastError());
closesocket(clientsocket);
WSACleanup();
}
}
|