Not surprisingly, but your program is doing what you told it to:
// Wait here for the user to enter a message
gets (msg);
while (msg != "q")
{
/* Write out message. */
if (write(sock, msg, sizeof(msg)) < 0)
pdie("Writing on stream socket");
/* Prepare buffer and read from it. */
bzero(buf, sizeof(buf));
if (read(sock, buf, BUFFER_SIZE) < 0)
pdie("Reading stream message");
printf("User %d says: %s\n", name, buf);
// Wait here for the user to enter a message
gets(msg);
}
If you're wanting the client to be both waiting for user input and watching for messages from the server (other client) you will need to implement some form of multi-threading.
One implementation might have a thread that supports the socket and the main display of the chat. (It would add lines to the window as they were received or sent.) Another thread would support the user input, it would wait for the user to enter some data (without blocking the other thread) and then send the message the user entered to the other thread for sending to the server and adding to the chat window.
As an alternative to 'actual' multi-threading, you might be able to do something with a 'main loop' that would check for user input and check for socket data repeatedly. Something like the following:
loop forever
if there is user input data available:
if the user input is an 'enter':
if the input buffer contains 'q':
break the loop
send the input buffer
else if the user input is a 'backspace':
if the input buffer is not empty:
remove the last character from the input buffer
else if the user input is a printable character:
add the character to the input buffer
if the socket is closed:
break the loop
if the socket has data:
read the data from the socket
display the data to the user