-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathFirstClient.c
More file actions
176 lines (156 loc) · 5.12 KB
/
FirstClient.c
File metadata and controls
176 lines (156 loc) · 5.12 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
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#include <winsock2.h>
#include <ws2tcpip.h>
#include <pthread.h>
#pragma comment(lib, "Ws2_32.lib")
/*
* Thread argument structure.
* This structure holds the socket used to communicate with the server.
*/
struct thread_args {
SOCKET sock; /* Socket connected to the server */
};
/*
* Thread function: Continuously receives messages from the server.
* - Messages received from the server are displayed in the console.
* - If the server sends an "Exit Server" message or disconnects, the thread exits.
*
* This function runs in its own thread to ensure the client can both
* send and receive messages simultaneously.
*/
void *receive_thread(void *arg) {
struct thread_args *t = arg;
SOCKET sock = t->sock;
free(t); /* Free dynamically allocated thread arguments */
char buffer[1024];
for (;;) {
/*
* Receive data from the server.
* - If `recv()` returns <= 0, the connection has been lost, and the thread exits.
*/
int n = recv(sock, buffer, (int)(sizeof(buffer) - 1), 0);
if (n <= 0) {
printf("[DEBUG] Disconnected from the server.\n");
exit(0); /* Exit the process */
}
buffer[n] = '\0'; /* Null-terminate the received string */
/*
* Check for the "Exit Server" command from the server.
* If received, exit the process.
*/
if (strcmp(buffer, "Exit Server") == 0) {
printf("[DEBUG] Server shutdown message received. Exiting.\n");
exit(0);
}
/* Print the received message to the console */
printf("[RECEIVED] From server/other client: %s\n", buffer);
}
return NULL; /* This point is never reached */
}
int main(int argc, char *argv[]) {
/*
* Check command-line arguments.
* - The user must provide the server's IP address as an argument.
*/
if (argc != 2) {
fprintf(stderr, "Usage: %s <server_ip>\n", argv[0]);
return 1;
}
/*
* Initialize WinSock.
* - Required for using sockets on Windows.
* - MAKEWORD(2, 2) specifies version 2.2 of the API.
*/
WSADATA wsa_data;
if (WSAStartup(MAKEWORD(2, 2), &wsa_data) != 0) {
fprintf(stderr, "Failed to initialize WinSock.\n");
return 1;
}
/*
* Create a socket for communicating with the server.
* - SOCK_STREAM indicates a TCP connection.
*
SOCKET sock = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
if (sock == INVALID_SOCKET) {
fprintf(stderr, "Socket creation failed: %d\n", WSAGetLastError());
WSACleanup();
return 1;
}
/*
* Configure the server's address and port.
* - Use designated initializers for clarity and maintainability.
*/
struct sockaddr_in srv = {
.sin_family = AF_INET,
.sin_port = htons(8080) /* Convert port to network byte order */
};
/*
* Convert the server's IP address from string to binary format.
* - `inet_pton()` returns <= 0 if the conversion fails.
*/
if (inet_pton(AF_INET, argv[1], &srv.sin_addr) <= 0) {
fprintf(stderr, "Invalid server address.\n");
closesocket(sock);
WSACleanup();
return 1;
}
/*
* Connect to the server.
* - If the connection fails, clean up and exit.
*/
if (connect(sock, (struct sockaddr *)&srv, sizeof(srv)) == SOCKET_ERROR) {
fprintf(stderr, "Connection to server failed: %d\n", WSAGetLastError());
closesocket(sock);
WSACleanup();
return 1;
}
printf("[DEBUG] Connected as FirstClient.\n");
/*
* Create a separate thread for receiving messages from the server.
* - The main thread remains available for user input and sending messages.
*/
struct thread_args *targs = calloc(1, sizeof(*targs));
targs->sock = sock;
pthread_t recv_tid;
if (pthread_create(&recv_tid, NULL, receive_thread, targs) != 0) {
fprintf(stderr, "Failed to create receive thread.\n");
free(targs);
closesocket(sock);
WSACleanup();
return 1;
}
/*
* Main thread handles user input.
* - Messages typed by the user are sent to the server.
* - If the user types "Exit Server," the client exits.
*/
char input[1024];
while (fgets(input, sizeof(input), stdin)) {
/*
* Remove trailing newline character from the input string.
* - This ensures the server receives a clean message.
*/
char *nl = strchr(input, '\n');
if (nl) *nl = '\0';
/* Send the user's message to the server */
send(sock, input, (int)strlen(input), 0);
/*
* Check for the "Exit Server" command.
* - If the user types this command, the client exits.
*/
if (strcmp(input, "Exit Server") == 0) {
printf("[DEBUG] 'Exit Server' command sent. Exiting.\n");
break;
}
}
/*
* Cleanup resources before exiting.
* - Close the socket and terminate WinSock.
*/
closesocket(sock);
WSACleanup();
return 0;
}