Forráskód Böngészése

vccd: now ok again

intirain 4 éve
szülő
commit
8c1444e86c
2 módosított fájl, 29 hozzáadás és 3 törlés
  1. 1 1
      include/vcc/version.h
  2. 28 2
      vcc.c

+ 1 - 1
include/vcc/version.h

@@ -1 +1 @@
-#define VCCD_VERSION "vccd 0.1.0 Sat Mar  5 15:51:51 CST 2022 root"
+#define VCCD_VERSION "vccd 0.1.0 Sat Mar  5 16:40:31 CST 2022 root"

+ 28 - 2
vcc.c

@@ -40,10 +40,13 @@
 
 
 struct klist_node connections = KLIST_NODE_INIT(&connections);
-
+int vcc_message_broadcast(char *msg);
+int nusers = 0;
 
 int vcc_new_connection(int fd, struct in_addr *addr) {
 	struct klist_node *n;
+	char *new_msg;
+	const static char join_msg[] = {"system: New user from %s joined. Now there are %d users. \n"};
 
 	vcc_log("New connection from %s\n", inet_ntoa(*addr));
 
@@ -66,17 +69,37 @@ int vcc_new_connection(int fd, struct in_addr *addr) {
 	klist_init(n->sending);	
 	klist_add(&connections, n);
 
+	if (unlikely(!(new_msg = malloc(128)))) {
+		vcc_log("*** malloc() failed\n");
+
+		return 1;
+	}
+
+	sprintf(new_msg, join_msg, inet_ntoa(*addr), ++nusers);
+	vcc_message_broadcast(new_msg);
+
+	free(new_msg);
+
 	return 0;
 }
 
 
 int vcc_close_connection(int fd) {
 	struct klist_node *n, *t;
+	const static char leave_msg[] = {"system: A user left, now there are only %d users here. \n"};
+	char *new_msg;
 
 	for (n = connections.next; n != &connections 
 			&& n->value != fd; n = n->next) 
 		;
 
+	if (unlikely(!(new_msg = malloc(128)))) {
+		vcc_log("*** malloc() failed\n");
+
+		return 1;
+	}
+
+	sprintf(new_msg, leave_msg, --nusers);
 	klist_del(&connections, n);
 
 	for (t = n->sending->next; t != n->sending; t = n->next) 
@@ -86,6 +109,9 @@ int vcc_close_connection(int fd) {
 
 	vcc_log("Client closed. \n");
 
+	vcc_message_broadcast(new_msg);
+	free(new_msg);
+
 	return 0;
 }
 
@@ -173,7 +199,7 @@ int vcc_message_broadcast(char *msg) {
 
 
 int vcc_new_msg(int fd, char *msg) {
-	if (((unsigned char *) msg)[0] == 0xffu) 
+	if (((unsigned char *) msg)[0] == 0xffu || !*msg) 
 		return 0;
 
 	vcc_log("New message: %s\n", msg);