Commit before breaking everything
[matches/honours.git] / research / transmission_spectroscopy / TOF / Win32++ / samples / Networking / Simple / Server.cpp
1 //////////////////////////////////////////////\r
2 // Server.cpp\r
3 \r
4 #include <iostream>\r
5 #include <string>\r
6 #include "winsock2.h"\r
7 #include "socket.h"\r
8 \r
9 using namespace std;\r
10 using namespace Win32xx;\r
11 \r
12 \r
13 class CServerSocket : public CSocket\r
14 {\r
15 public:\r
16         CServerSocket() {}\r
17         virtual ~CServerSocket() {}\r
18         virtual void OnReceive()\r
19         {\r
20                 // This function is called automatically when there is data to receive\r
21                 char str[1024] = {0};\r
22                 int i = Receive(str, 1024, 0);\r
23                 cout << i <<" chars received: " << str << endl;\r
24         }\r
25 };\r
26 \r
27 int main()\r
28 {\r
29         // Create the main server socket.\r
30         // It is used to listen for clients\r
31         CServerSocket Server;\r
32         if (!Server.Create(AF_INET, SOCK_STREAM))\r
33         {\r
34                 cout << "Failed to create socket\n" ;\r
35                 return 0;\r
36         }\r
37 \r
38         // Bind the IP address and port# to the main socket\r
39         if (SOCKET_ERROR == Server.Bind("127.0.0.1", "3000"))\r
40         {\r
41                 cout << "Failed to bind IP address to socket\n" ;\r
42                 return 0;\r
43         }\r
44 \r
45         // Listen on the socket for clients to connect\r
46         if (SOCKET_ERROR == Server.Listen())\r
47         {\r
48                 cout << "Listen on socket failed\n";\r
49                 return 0;\r
50         }\r
51 \r
52         // Create the socket to communicate with the Client\r
53         CServerSocket Client;\r
54         cout << "Waiting for the client to connect\n";\r
55         do\r
56         {\r
57                 Server.Accept(Client, NULL, NULL);\r
58         }\r
59         while (SOCKET_ERROR == Client.GetSocket());\r
60 \r
61         cout << "Client connected\n";\r
62 \r
63         // Monitor the client socket for network events, such as data ready to receive\r
64         Client.StartEvents();\r
65 \r
66         // Send data to the client\r
67         cout << "Type data to send, type quit to exit\n";\r
68         string s;\r
69         for (;;)   // infinite loop\r
70         {\r
71                 getline(cin, s);\r
72                 if (s == "quit") break;\r
73                 int i = Client.Send(s.c_str(), (int)s.length(), 0);\r
74                 cout << "Sending  " << i << " characters\n";\r
75         }\r
76 \r
77         return 0;\r
78 }\r
79 \r

UCC git Repository :: git.ucc.asn.au