0

We have to program a server and a client using event-driven programming - we use select(2) to read from stdin and sockets. I'm making an interface for the client using the SDL2 and SDL2_TTF libraries. The problem is I don't know how to make select(2) work for SDL text input events, so I cannot connect the client to my interface. How should I do that? Is there a file descriptor I can use to watch my input on the SDL window?

I forgot to mention: we have to use select(2)

genpfault
  • 51,148
  • 11
  • 85
  • 139
liara
  • 13
  • 3

2 Answers2

2

Is there a file descriptor I can use to watch my input on the SDL window?

Nope. Best you can do is get some platform-specific window handles via SDL_GetWindowWMInfo() & the SDL_SysWMinfo struct.

You might be able to use ConnectionNumber() on x11.display and select(2) on it but that's really X11-specific.

How should I do that?

Have the main/GUI/SDL thread send messages to your networking thread via write(2) on a local socket which the networking thread also select(2)s on. For network thread to main thread communication you can use SDL_PushEvent() with a custom event to wake up SDL_WaitEvent().

genpfault
  • 51,148
  • 11
  • 85
  • 139
0

SDL has a polling based event handling so you'll basically want a loop as in

while (!quitting) {
 pollEvents();
 drawEverything();
 delayForFPS();
}

How to poll for events and how to manage text input events is explained everywhere on SDL tutorials as in this one or here, but basically it's something like:

SDL_Event event;
if (SDL_PollEvent(&event)) {
  if (event.type == SDL_TEXTINPUT) {
   std::string text = event.text.text;
  }
}

So there is no stdin or select involved at all.

Mind that since you need networking features the above loop may include pollForPendingPackets() and dispatchPackets() phases which take this into account.

A good approach would be to have the networking thread receive all packets and queue them in a buffer which is then handled by the SDL thread.

Jack
  • 131,802
  • 30
  • 241
  • 343
  • I forgot to mention that the assignment specifically tell us to use select from sys/types.h, so I have to use it – liara Nov 06 '17 at 21:46
  • indeed you will use `select` to manage sockets, not to handle `stdin`. – Jack Nov 06 '17 at 21:48