discard.c
[reactos.git] / reactos / apps / utils / net / tcpsvcs / echo.c
1 #include <stdio.h>
2 #include <winsock2.h>
3 #include <tchar.h>
4 #include "tcpsvcs.h"
5
6 DWORD WINAPI EchoHandler(VOID* Sock_)
7 {
8 DWORD Retval = 0;
9 SOCKET Sock = (SOCKET)Sock_;
10
11 if (!EchoIncomingPackets(Sock)) {
12 _tprintf(_T("Echo incoming packets failed\n"));
13 Retval = 3;
14 }
15
16 _tprintf(_T("Shutting connection down...\n"));
17 if (ShutdownConnection(Sock, TRUE)) {
18 _tprintf(_T("Connection is down.\n"));
19 }
20 else
21 {
22 _tprintf(_T("Connection shutdown failed\n"));
23 Retval = 3;
24 }
25 _tprintf(_T("Terminating thread\n"));
26 ExitThread(0);
27
28 return Retval;
29 }
30
31
32
33 BOOL EchoIncomingPackets(SOCKET Sock)
34 {
35 TCHAR ReadBuffer[BUF];
36 INT Temp;
37 INT ReadBytes;
38 INT SentBytes;
39
40 do {
41 ReadBytes = recv(Sock, ReadBuffer, BUF, 0);
42 if (ReadBytes > 0)
43 {
44 _tprintf(_T("Received %d bytes from client\n"), ReadBytes);
45
46 SentBytes = 0;
47 while (SentBytes < ReadBytes)
48 {
49 Temp = send(Sock, ReadBuffer + SentBytes,
50 ReadBytes - SentBytes, 0);
51 if (Temp > 0)
52 {
53 _tprintf(_T("Sent %d bytes back to client\n"), Temp);
54 SentBytes += Temp;
55 }
56 else if (Temp == SOCKET_ERROR)
57 return FALSE;
58 else
59 {
60 /* Client closed connection before we could reply to
61 all the data it sent, so quit early. */
62 _tprintf(_T("Peer unexpectedly dropped connection!\n"));
63 return FALSE;
64 }
65 }
66 }
67 else if (ReadBytes == SOCKET_ERROR)
68 return FALSE;
69
70 } while (ReadBytes != 0);
71
72 _tprintf(("Connection closed by peer.\n"));
73 return TRUE;
74 }