Skip to content
Advertisement

How can I stop the while?

I have A TCP Server-Client where I enter a number with the number of times that I want to send the word to the server. So I send correctly because I print the information on a loop(in client) but in the server shows infinitely because I put while(1) but if I don’t use just print it one time. I don’t want to send the number to the server.

If I enter the number 4 I want to print the word “hello” four times This is the server, now it’s printing infinitely obviously.

JavaScript

This is the client

JavaScript

Advertisement

Answer

There are multiple problems in you code:

  • you do not test if read() succeeds. You should break from the loop if it fails.
  • you unconditionally close the socket in the body of the loop: the next read will fail and return -1 immediately, you will print a bogus message and iterate at nauseam.
  • you call strlen() and printf() with a buffer that might not be null terminated, potentially causing undefined behavior.

Here is a modified version:

JavaScript
User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement