-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathServer5.c
More file actions
225 lines (191 loc) · 6.82 KB
/
Server5.c
File metadata and controls
225 lines (191 loc) · 6.82 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
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <winsock2.h>
#include <ws2tcpip.h>
#include <pthread.h>
#pragma comment(lib, "Ws2_32.lib")
/* Intrusive Linked List Node
* future proofs as I can add more clients if I want
*/
struct llist_node {
struct llist_node *next;
};
/* Linked List Head */
struct llist_head {
struct llist_node *first;
};
/* Macro for Iterating Over the List
* this saves time as I can reuse this to traverse the list
* also future proofs as I can add more clients if I want
*/
#define llist_for_each(pos, head) \
for (struct llist_node *pos = (head)->first; pos != NULL; pos = pos->next)
/* Client Node Structure */
struct client_node {
struct llist_node node; /* Intrusive linked list node */
SOCKET socket; /* Client socket */
pthread_t thread; /* Thread handling this client */
struct client_node *peer; /* Pointer to the peer client (not strictly needed for broadcasting) */
};
/* Global client list so it can be accessed in thread function */
static struct llist_head client_list = { .first = NULL };
/* Function to broadcast a message to all clients except the sender
* this for future proofing
* so in the future you can add more clients
*/
void broadcast_message(struct llist_head *list, struct client_node *sender, const char *message, size_t length) {
struct llist_node *pos;
llist_for_each(pos, list) {
struct client_node *client = (struct client_node *)pos;
if (client != sender) { // Skip the sender
send(client->socket, message, (int)length, 0);
}
}
}
/* Function to print all connected clients */
void print_all_clients(struct llist_head *list) {
printf("[INFO] Currently connected clients:\n");
struct llist_node *pos;
llist_for_each(pos, list) {
struct client_node *client = (struct client_node *)pos;
printf(" - Socket: %d\n", client->socket);
}
}
/* Function to count the number of connected clients */
int count_clients(struct llist_head *list) {
int count = 0;
struct llist_node *pos;
llist_for_each(pos, list) {
count++;
}
return count;
}
/* Thread Function to Handle Client Communication */
void *client_thread(void *arg) {
struct client_node *self = (struct client_node *)arg;
SOCKET my_sock = self->socket;
char buffer[1024];
for (;;) {
int n = recv(my_sock, buffer, (int)(sizeof(buffer) - 1), 0);
if (n <= 0) { /* Client disconnected */
printf("[INFO] Client disconnected (Socket: %d).\n", my_sock);
closesocket(my_sock);
/* Optionally: Notify the peer or do any cleanup here.
* For this example, we just exit the thread.
*/
pthread_exit(NULL);
}
buffer[n] = '\0';
printf("[MESSAGE] Client (Socket: %d): %s\n", my_sock, buffer);
/* Broadcast the message to all other clients */
broadcast_message(&client_list, self, buffer, n);
}
return NULL;
}
/* Accept New Client and Add to the Linked List */
struct client_node *accept_client(SOCKET listen_socket, struct llist_head *list) {
SOCKET client_sock = accept(listen_socket, NULL, NULL);
if (client_sock == INVALID_SOCKET) {
fprintf(stderr, "Accept failed: %d\n", WSAGetLastError());
return NULL;
}
printf("[INFO] New client connected (Socket: %d).\n", client_sock);
/* Allocate and initialize a new client node */
struct client_node *new_client = calloc(1, sizeof(*new_client));
if (!new_client) {
fprintf(stderr, "Out of memory.\n");
closesocket(client_sock);
return NULL;
}
new_client->socket = client_sock;
/* Add the new client to the linked list */
new_client->node.next = list->first;
list->first = &new_client->node;
return new_client;
}
int main(void) {
WSADATA wsa_data;
if (WSAStartup(MAKEWORD(2, 2), &wsa_data) != 0) {
fprintf(stderr, "Failed to initialize WinSock.\n");
return EXIT_FAILURE;
}
/* Create a listening socket */
SOCKET listen_socket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
if (listen_socket == INVALID_SOCKET) {
fprintf(stderr, "Socket creation failed: %d\n", WSAGetLastError());
WSACleanup();
return EXIT_FAILURE;
}
/* Configure server address */
struct sockaddr_in server_addr;
memset(&server_addr, 0, sizeof(server_addr));
server_addr.sin_family = AF_INET;
server_addr.sin_port = htons(8080);
server_addr.sin_addr.s_addr = INADDR_ANY;
/* Bind socket */
if (bind(listen_socket, (struct sockaddr *)&server_addr, sizeof(server_addr)) == SOCKET_ERROR) {
fprintf(stderr, "Bind failed: %d\n", WSAGetLastError());
closesocket(listen_socket);
WSACleanup();
return EXIT_FAILURE;
}
/* Start listening */
if (listen(listen_socket, SOMAXCONN) == SOCKET_ERROR) {
fprintf(stderr, "Listen failed: %d\n", WSAGetLastError());
closesocket(listen_socket);
WSACleanup();
return EXIT_FAILURE;
}
printf("[INFO] Server started. Waiting for two clients...\n");
/* Accept the first client */
struct client_node *clientA = accept_client(listen_socket, &client_list);
if (!clientA) {
closesocket(listen_socket);
WSACleanup();
return EXIT_FAILURE;
}
/* Accept the second client */
struct client_node *clientB = accept_client(listen_socket, &client_list);
if (!clientB) {
closesocket(clientA->socket);
free(clientA);
closesocket(listen_socket);
WSACleanup();
return EXIT_FAILURE;
}
/* Print all connected clients and their count */
print_all_clients(&client_list);
printf("[INFO] Total clients connected: %d\n", count_clients(&client_list));
/* Create threads for both clients */
if (pthread_create(&clientA->thread, NULL, client_thread, clientA) != 0) {
fprintf(stderr, "Failed to create thread for Client A.\n");
closesocket(clientA->socket);
closesocket(clientB->socket);
free(clientA);
free(clientB);
closesocket(listen_socket);
WSACleanup();
return EXIT_FAILURE;
}
if (pthread_create(&clientB->thread, NULL, client_thread, clientB) != 0) {
fprintf(stderr, "Failed to create thread for Client B.\n");
closesocket(clientA->socket);
closesocket(clientB->socket);
free(clientA);
free(clientB);
closesocket(listen_socket);
WSACleanup();
return EXIT_FAILURE;
}
/* Wait for both threads to finish */
pthread_join(clientA->thread, NULL);
pthread_join(clientB->thread, NULL);
/* Clean up resources */
closesocket(listen_socket);
free(clientA);
free(clientB);
WSACleanup();
printf("[INFO] Server shutdown complete.\n");
return EXIT_SUCCESS;
}