-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcmine.cpp
More file actions
102 lines (83 loc) · 2.37 KB
/
cmine.cpp
File metadata and controls
102 lines (83 loc) · 2.37 KB
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
#include <iostream>
#include <string>
#include <unistd.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <cstring>
#include <signal.h>
using namespace std;
int sock = -1;
// Signal handler for Ctrl+C
void handle_sigint(int sig) {
cout << "\nCaught Ctrl+C, Disconnecting from the server\n";
if (sock != -1) {
const char* msg = "A client got disconnected\n";
send(sock, msg, strlen(msg), 0);
close(sock);
}
exit(0);
}
int main() {
sock = socket(AF_INET, SOCK_STREAM, 0);
if (sock == -1) {
cerr << "❌ Socket creation failed\n";
return 1;
}
signal(SIGINT, handle_sigint);
struct sockaddr_in server;
server.sin_family = AF_INET;
server.sin_port = htons(8050);
server.sin_addr.s_addr = inet_addr("127.0.0.1");
if (connect(sock, (struct sockaddr*)&server, sizeof(server)) < 0) {
cerr << "❌ Connection failed\n";
return 1;
}
cout << "✅ Connected to the server!\n";
char buffer[8192];
while (true) {
memset(buffer, 0, sizeof(buffer));
// Receive message from server
int bytesReceived = recv(sock, buffer, sizeof(buffer) - 1, 0);
if (bytesReceived <= 0) {
cout << "🔌 Server disconnected.\n";
break;
}
buffer[bytesReceived] = '\0';
string message(buffer);
// ✅ Always print the server message
cout << message;
// ✅ Check for the explicit prompt marker
if (message.rfind("PROMPT@") != string::npos &&
message.length() >= 7 &&
message.substr(message.length() - 7) == "PROMPT@") {
string input;
int blankCount = 0;
while (true) {
cout << "> ";
getline(cin, input);
// Trim the input
size_t start = input.find_first_not_of(" \t\r\n");
if (start == string::npos) {
blankCount++;
if (blankCount == 1) {
cout << "⚠️ Empty input. Please enter again:\n";
continue; // prompt again
} else {
// Send a space to keep sync and inform server it's junk
input = " ";
break;
}
} else {
break; // valid input
}
}
input += '\n';
if (send(sock, input.c_str(), input.length(), 0) == -1) {
cerr << "❌ Failed to send input\n";
break;
}
}
}
close(sock);
return 0;
}