1
0
tcp-number-guessing/109062273_cli.cpp

113 lines
2.8 KiB
C++

#include <iostream>
#include <sstream>
#include <string>
#include <cstring>
#include <cstdlib>
#include <unistd.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#define BUFFER_SIZE 256
#define NOSERVER_RET 10
#define INVALID_PORT_RET 20
#define CONN_FAILED_RET 30
using namespace std;
int main(int argc, char const *argv[]) {
// no server info specified
if (argc < 2) {
cerr << "No server info provided!" << endl << "Usage: client <ip> <port>" << endl;
return NOSERVER_RET;
}
int port = atoi(argv[2]);
if (port < 0 || port >= 65536) {
cerr << "Invalid port! port range: 0 ~ 65535" << endl;
return INVALID_PORT_RET;
}
int sockfd = 0;
struct sockaddr_in info;
// create tcp socket
sockfd = socket(AF_INET, SOCK_STREAM, 0);
if (sockfd == -1) {
cerr << "Failed to create socket." << endl;
}
// setup server info
bzero(&info, sizeof(info));
info.sin_family = PF_INET;
info.sin_addr.s_addr = inet_addr(argv[1]);
info.sin_port = htons(port);
if (connect(sockfd, (struct sockaddr *) &info, sizeof(info)) == -1) {
cerr << "Connection failed." << endl;
close(sockfd);
return CONN_FAILED_RET;
}
cout << "--------------" << endl;
cout << " Game start " << endl;
cout << "--------------" << endl;
while (true) {
// ask for input
cout << "Guess: ";
string number;
cin >> number;
// create payload
const char * msg = number.c_str();
#ifdef DEBUG
cout << msg << endl;
#endif
if (send(sockfd, msg, sizeof(msg), 0) == -1) {
cerr << "Send error" << endl;
break;
};
// receive server response
char buffer[BUFFER_SIZE];
memset(buffer, 0, sizeof(buffer));
int size = recv(sockfd, buffer, sizeof(buffer), 0);
if (size <= 0) {
cout << "Connection ended." << endl;
break;
}
#ifdef DEBUG
cout << buffer << endl;
#endif
// parse message from server
stringstream ss(buffer);
string lower, upper, count;
getline(ss, lower, ':');
getline(ss, upper, ':');
getline(ss, count, ':');
if (lower == upper) {
// win, start new turn
cout << "Answer Correct. Guessed for " << count << " times." << endl;
cout << endl;
cout << "--------------" << endl;
cout << " New Turn " << endl;
cout << "--------------" << endl;
continue;
}
cout << "Answer is fewer than " << upper << endl;
cout << "Answer is more than " << lower << endl;
// space
cout << endl;
}
close(sockfd);
return 0;
}