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

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

Made the client able to compile on linux

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