'How to make a GTK application that receives data from a TCP socket

I am building a GUI (using C) which receives data to display from another application sending the data over a TCP socket. How do I do this using GTK (just a general overview of the approach I should take)? I have done a lot of searching and came across stuff about multithreading, GIOchannel etc. now I'm more confused than ever. There doesn't seem to be any conclusive articles or guides about how to actually achieve this.



Solution 1:[1]

There is basically one important rule:

You must call all gtk_* functions from the main thread.

If you update any widgets from another thread, you might get inconsistent results.

Of course, you don't want to wait for TCP data in that thread.

Therefore I would suggest you create a separate thread for doing the communication. In this thread you can wait for data and if you got anything that should affect what you show in your GUI, you can tell the main thread to do the required work.

A simple way to do this is to use g_idle_add() to enqueue a callback function. That callback function is then executed in context of main thread and can update your widgets. The information what needs to be updated can be stored in some newly allocated memory that is passed to this callback where you have to free it afterwards.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Gerhardh