Search code examples
csocketstcpgetcharrecv

Getchar() from client in socket programming


I am creating a C program that is run from a raspberry pi that can take commands from a telnet terminal (putty) from a client (other PC/Laptop) which is connected through a TCP/IP connection (socket programming) and process those commands to run a motor which is connected to the RPi. This means I only need to create a server code to be run in the RPi, and not a client code.

My question is, can there be a way so that I can use getchar() on the inputs from the client (should only be coded from the server side)? Could it be used with recv()?

The reason I need to use getchar() is because I have this algorithm in mind that reads each character from the client before they press enter, which allows me to differentiate the clients' commands from the arguments.

Thanks in advance!


Solution

  • If I read the question right your problem is to read input from the client before they press enter.

    In that case the answer is no. Even if you jump through the hoops to use getchar on the server side that won't change the client, which will be causing your problem. If the client only sends data when the user presses enter then nothing in the server can fix that.

    If that isn't the problem and you only want to read input one char at a time them simply specify a size of 1 for recv(). It will be hugely inefficient but it's not like users type that fast. It only becomes a problem when later users start to script things and want to send many commands per second. Note: You can use fdopen() to create a FILE* from a socket and use getc() to have the libc buffer input for you and have a getchar() equivalent.

    Either way getchar() isn't the way to go.