7 DWORD WINAPI
StartServer(LPVOID lpParam
)
9 const TCHAR
* HostIP
= "127.0.0.1";
14 pServices
= (PSERVICES
)lpParam
;
16 if ((RetVal
= WSAStartup(MAKEWORD(2, 2), &wsaData
)) != 0)
18 _tprintf(_T("WSAStartup() failed : %lu\n"), RetVal
);
22 SOCKET ListeningSocket
= SetUpListener(HostIP
, htons(pServices
->Port
));
23 if (ListeningSocket
== INVALID_SOCKET
)
25 _tprintf(_T("error setting up socket\n"));
29 _tprintf(_T("Waiting for connections...\n"));
32 AcceptConnections(ListeningSocket
, pServices
->Service
);
33 printf("Acceptor restarting...\n");
36 /* won't see this yet as we kill the service */
37 _tprintf(_T("Detaching Winsock2...\n"));
43 SOCKET
SetUpListener(const char* ServAddr
, int Port
)
48 Sock
= socket(AF_INET
, SOCK_STREAM
, 0);
49 if (Sock
!= INVALID_SOCKET
)
51 Server
.sin_family
= AF_INET
;
52 Server
.sin_addr
.s_addr
= htonl(INADDR_ANY
);
53 Server
.sin_port
= Port
;
54 if (bind(Sock
, (SOCKADDR
*)&Server
, sizeof(SOCKADDR_IN
)) != SOCKET_ERROR
)
56 listen(Sock
, SOMAXCONN
);
60 printf("bind() failed\n");
63 return INVALID_SOCKET
;
69 VOID
AcceptConnections(SOCKET ListeningSocket
, LPTHREAD_START_ROUTINE Service
)
73 INT nAddrSize
= sizeof(Client
);
78 Sock
= accept(ListeningSocket
, (SOCKADDR
*)&Client
, &nAddrSize
);
79 if (Sock
!= INVALID_SOCKET
)
81 _tprintf(_T("Accepted connection from %s:%d\n"),
82 inet_ntoa(Client
.sin_addr
), ntohs(Client
.sin_port
));
83 _tprintf(_T("About to create thread\n"));
84 CreateThread(0, 0, Service
, (void*)Sock
, 0, &ThreadID
);
88 _tprintf(_T("accept() failed\n"));
94 BOOL
ShutdownConnection(SOCKET Sock
, BOOL bRec
)
96 /* Disallow any further data sends. This will tell the other side
97 that we want to go away now. If we skip this step, we don't
98 shut the connection down nicely. */
99 if (shutdown(Sock
, SD_SEND
) == SOCKET_ERROR
)
101 _tprintf(_T("Error in shutdown"));
105 /* Receive any extra data still sitting on the socket. After all
106 data is received, this call will block until the remote host
107 acknowledges the TCP control packet sent by the shutdown above.
108 Then we'll get a 0 back from recv, signalling that the remote
109 host has closed its side of the connection. */
112 char ReadBuffer
[BUF
];
113 int NewBytes
= recv(Sock
, ReadBuffer
, BUF
, 0);
114 if (NewBytes
== SOCKET_ERROR
)
116 else if (NewBytes
!= 0)
117 _tprintf(_T("FYI, received %d unexpected bytes during shutdown\n"), NewBytes
);
120 /* Close the socket. */
121 if (closesocket(Sock
) == SOCKET_ERROR
)