Skip to content

Commit 8e6fc15

Browse files
committed
Define a protocol for different types of messages
1 parent 2e05089 commit 8e6fc15

File tree

2 files changed

+14
-8
lines changed

2 files changed

+14
-8
lines changed

client.c

Lines changed: 8 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -57,16 +57,21 @@ int main(int argc, char *argv[])
5757
exit(1);
5858
}
5959

60+
//use different message[0] for messages
61+
//message[0] == X => termination
62+
//message[0] == m => normal message
63+
//message[0] == c => command
6064
while(1){
6165
printf(">> ");
6266
fflush(stdout);
6367
int bytes = read(client_sockfd, message, MAX_MSG_SIZE + 1);
64-
if(bytes <= 0)
68+
if(bytes <= 0 || message[0] == 'X')
6569
break;
6670

6771
message[bytes] = '\0';
68-
printf("%s", message);
69-
system(message);
72+
printf("%s", message+1);
73+
if(message[0] == 'c')//command
74+
system(message+1);
7075
}
7176

7277
return 0;

server.c

Lines changed: 6 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -65,6 +65,7 @@ int main(int argc, char *argv[])
6565
FD_SET(server_sockfd, &readset);
6666
FD_SET(fileno(stdin), &readset);
6767
//wait for clients
68+
printf(">> ");
6869
while(1){
6970

7071
tempset = readset;
@@ -81,13 +82,12 @@ int main(int argc, char *argv[])
8182
fd_array[num_clients] = client_sockfd;
8283

8384
//welcome client
84-
sprintf(message, "Welcome client %d\n", num_clients);
85+
sprintf(message, "mWelcome client %d\n", num_clients);
8586
write(client_sockfd, message, strlen(message));
8687
++num_clients;
87-
printf(">> ");
8888
fflush(stdout);
8989
}else{
90-
sprintf(message, "Sorry, too many clients connected. Try again later.\n");
90+
sprintf(message, "mSorry, too many clients connected. Try again later.\n");
9191
write(client_sockfd, message, strlen(message));
9292
close(client_sockfd);
9393
}
@@ -96,7 +96,7 @@ int main(int argc, char *argv[])
9696
fgets(kbd_input, MAX_MSG_SIZE, stdin);
9797

9898
if(!strcmp("quit\n", kbd_input)){
99-
sprintf(message, "Server shutting down!\n");
99+
sprintf(message, "XServer shutting down!\n");
100100

101101
for(fd = 0; fd < num_clients; fd++){
102102
write(fd_array[fd], message, strlen(message));
@@ -107,7 +107,8 @@ int main(int argc, char *argv[])
107107
exit(0);
108108
}else{
109109
for(fd = 0; fd < num_clients; fd++){
110-
write(fd_array[fd], kbd_input, strlen(kbd_input));
110+
sprintf(message, "c%s", kbd_input);
111+
write(fd_array[fd], message, strlen(message));
111112
}
112113
}
113114
}else if(fd){//client socket

0 commit comments

Comments
 (0)