-
Notifications
You must be signed in to change notification settings - Fork 0
/
client.cpp
107 lines (89 loc) · 2.63 KB
/
client.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
#include <iostream>
#include <winsock.h>
#include <fstream>
#include <thread>
#define PORT 9909
#define SIZE 1024
using namespace std;
int nClientSocket;
struct sockaddr_in srv;
char buff[SIZE] = { 0, };
int nRet = 0;
void cleanup() {
closesocket(nClientSocket);
WSACleanup();
}
void send_message() {
memset(buff, 0, sizeof(buff));
// Type text message
fgets(buff, SIZE, stdin);
buff[strcspn(buff, "\n")] = '\0';
nRet = send(nClientSocket, buff, strlen(buff), 0);
if (nRet == SOCKET_ERROR) {
int error = WSAGetLastError();
cout << "send() failed with error: " << error << endl;
if (error == WSAECONNRESET) {
cout << "Connection reset by server." << endl;
}
cleanup();
return;
}
memset(buff, 0, sizeof(buff)); // Clear buffer before receiving response
}
void receive_messages() {
while (true) {
memset(buff, 0, SIZE);
nRet = recv(nClientSocket, buff, SIZE, 0);
if (nRet <= 0) {
cout << "Connection closed by server." << endl;
cleanup();
exit(EXIT_FAILURE);
}
cout << buff << endl;
}
}
int main() {
WSADATA ws;
if (WSAStartup(MAKEWORD(2, 2), &ws) != 0) {
cout << "WSAStartup failed." << endl;
return(EXIT_FAILURE);
}
nClientSocket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
if (nClientSocket < 0) {
cout << "socket() call failed." << endl;
WSACleanup();
return (EXIT_FAILURE);
}
srv.sin_family = AF_INET;
srv.sin_port = htons(PORT);
srv.sin_addr.s_addr = inet_addr("127.0.0.1");
memset(&srv.sin_zero, 0, 8);
nRet = connect(nClientSocket, (struct sockaddr*)&srv, sizeof(srv));
if (nRet < 0) {
cout << "connect failed." << endl;
cleanup();
return (EXIT_FAILURE);
}
else {
cout << "Connected to the server." << endl;
// Receive initial message from the server
nRet = recv(nClientSocket, buff, SIZE, 0);
if (nRet <= 0) {
cout << "Failed to receive message from server or connection closed." << endl;
cleanup();
return EXIT_FAILURE;
}
cout << "Message received from the server: " << buff << endl;
// clearing buffer
memset(buff, 0, SIZE);
thread receiver(receive_messages);
receiver.detach();
cout << "Type message and hit enter to send it to others..." << endl;
cout << "-------------------------------" << endl << endl;
while (true) {
send_message();
}
}
cleanup();
return 0;
}