source: network-game/client/Client/main.cpp@ cb1f288

Last change on this file since cb1f288 was 6c92572, checked in by dportnoy <dmp1488@…>, 12 years ago

The client now keeps sending messages until the user quits

  • Property mode set to 100644
File size: 1.8 KB
Line 
1#include "../../common/compiler.h"
2
3#include <sys/types.h>
4
5#ifdef WINDOWS
6 #include <winsock2.h>
7 #include <WS2tcpip.h>
8#endif
9
10#include <stdio.h>
11#include <stdlib.h>
12#include <string>
13
14#include <iostream>
15
16#include <boost/lambda/lambda.hpp>
17
18#include "../../common/message.h"
19
20#ifdef WINDOWS
21 #pragma comment(lib, "ws2_32.lib")
22#endif
23
24using namespace std;
25
26void error(const char *);
27
28int main(int argc, char *argv[])
29{
30 int sock, n;
31 struct sockaddr_in server, from;
32 struct hostent *hp;
33 char buffer[256];
34 NETWORK_MSG msgTo, msgFrom;
35
36 if (argc != 3) {
37 cout << "Usage: server port" << endl;
38 exit(1);
39 }
40
41 WORD wVersionRequested;
42 WSADATA wsaData;
43 int wsaerr;
44
45 wVersionRequested = MAKEWORD(2, 2);
46 wsaerr = WSAStartup(wVersionRequested, &wsaData);
47
48 if (wsaerr != 0) {
49 cout << "The Winsock dll not found." << endl;
50 exit(1);
51 }else
52 cout << "The Winsock dll was found." << endl;
53
54 sock= socket(AF_INET, SOCK_DGRAM, 0);
55 if (sock < 0)
56 error("socket");
57
58 server.sin_family = AF_INET;
59 hp = gethostbyname(argv[1]);
60 if (hp==0)
61 error("Unknown host");
62
63 memcpy((char *)&server.sin_addr, (char *)hp->h_addr, hp->h_length);
64 server.sin_port = htons(atoi(argv[2]));
65
66 while(true) {
67 cout << "Please enter the message: ";
68 cin.getline(msgTo.buffer, 256);
69
70 if (strcmp(msgTo.buffer, "quit") == 0) {
71 break;
72 }
73
74 socklen_t socklen = sizeof(server);
75 n=sendMessage(&msgTo, sock, &server);
76 if (n < 0)
77 error("sendMessage");
78
79 n = receiveMessage(&msgFrom, sock, &from);
80 if (n < 0)
81 error("receiveMessage");
82
83 cout << msgFrom.buffer << endl;
84 }
85
86 cout << "Thank you for playing!" << endl;
87
88 closesocket(sock);
89
90 WSACleanup();
91
92 return 0;
93}
94
95// need to make a function like this that works on windows
96void error(const char *msg)
97{
98 perror(msg);
99 WSACleanup();
100 exit(1);
101}
Note: See TracBrowser for help on using the repository browser.