move tcpsvcs from the /apps directory to the /services directory
[reactos.git] / reactos / services / tcpsvcs / echo.c
1 /*
2 * ReactOS Services
3 * Copyright (C) 2005 ReactOS Team
4 *
5 * LICENCE: GPL - See COPYING in the top level directory
6 * PROJECT: ReactOS simple TCP/IP services
7 * FILE: apps/utils/net/tcpsvcs/echo.c
8 * PURPOSE: Provide CharGen, Daytime, Discard, Echo, and Qotd services
9 * PROGRAMMERS: Ged Murphy (gedmurphy@gmail.com)
10 * REVISIONS:
11 * GM 04/10/05 Created
12 *
13 */
14
15 #include <stdio.h>
16 #include <winsock2.h>
17 #include <tchar.h>
18 #include "tcpsvcs.h"
19
20 DWORD WINAPI EchoHandler(VOID* Sock_)
21 {
22 DWORD RetVal = 0;
23 SOCKET Sock = (SOCKET)Sock_;
24
25 if (!EchoIncomingPackets(Sock)) {
26 _tprintf(_T("Echo incoming packets failed\n"));
27 RetVal = -1;
28 }
29
30 _tprintf(_T("Shutting connection down...\n"));
31 if (ShutdownConnection(Sock, TRUE)) {
32 _tprintf(_T("Connection is down.\n"));
33 }
34 else
35 {
36 _tprintf(_T("Connection shutdown failed\n"));
37 RetVal = -1;
38 }
39
40 _tprintf(_T("Terminating echo thread\n"));
41 ExitThread(RetVal);
42 }
43
44
45
46 BOOL EchoIncomingPackets(SOCKET Sock)
47 {
48 TCHAR ReadBuffer[BUF];
49 INT Temp;
50 INT ReadBytes;
51 INT SentBytes;
52
53 do {
54 ReadBytes = recv(Sock, ReadBuffer, BUF, 0);
55 if (ReadBytes > 0)
56 {
57 _tprintf(_T("Received %d bytes from client\n"), ReadBytes);
58
59 SentBytes = 0;
60 while (SentBytes < ReadBytes)
61 {
62 Temp = send(Sock, ReadBuffer + SentBytes,
63 ReadBytes - SentBytes, 0);
64 if (Temp > 0)
65 {
66 _tprintf(_T("Sent %d bytes back to client\n"), Temp);
67 SentBytes += Temp;
68 }
69 else if (Temp == SOCKET_ERROR)
70 return FALSE;
71 else
72 {
73 /* Client closed connection before we could reply to
74 all the data it sent, so quit early. */
75 _tprintf(_T("Peer unexpectedly dropped connection!\n"));
76 return FALSE;
77 }
78 }
79 }
80 else if (ReadBytes == SOCKET_ERROR)
81 return FALSE;
82
83 } while (ReadBytes != 0);
84
85 _tprintf(("Connection closed by peer.\n"));
86 return TRUE;
87 }