Re: Using GSocket in a GTK application
- From: Jacques Pelletier <jpelletier ieee org>
- To: gtk-app-devel-list gnome org
- Subject: Re: Using GSocket in a GTK application
- Date: Tue, 22 Feb 2011 23:25:43 -0500
On Sunday 13 February 2011 22:17:12 Jacques Pelletier wrote:
Hi all,
I'm using GSocket in a GTK application in non-blocking mode.
Once the connection is done, I'm creating a source for the main event loop:
my_source = g_socket_create_source(my_socket, my_events, NULL);
How do we specify a callback? Should I use g_source_set_callback ()?
The callback would handle the input side from the host to my application.
I've been able to work this out. Here is how I implemented the client side:
...
/* Connect asynchronously */
mySocketClient = g_socket_client_new();
g_socket_client_connect_to_host_async(
mySocketClient,
myUrl,
myPort,
NULL,
my_client_connect_async_function,
NULL);
...
void my_client_connect_async_function(GObject *source_object,
GAsyncResult *res,
gpointer user_data)
{
mySocketConnection =
g_socket_client_connect_to_host_finish(source_object,res,NULL);
if (mySocketConnection != NULL)
{
mySocket = g_socket_connection_get_socket(mySocketConnection);
mySource = g_socket_create_source(mySocket,
G_IO_IN | G_IO_PRI | G_IO_NVAL,
NULL);
g_source_set_callback(mySource, myCallback,NULL,NULL);
mySource_id = g_source_attach(mySource,NULL);
/* Instructions for updating the GUI */
}
else
{
/* Socket connection failed */
}
}
/* Process incoming data from socket */
gboolean myCallback(GSocket *source, GIOCondition condition, gpointer data)
{
int Input_Length;
gchar Receive_Buffer[1024];
switch (condition)
{
/* Check for socket error */
case (G_IO_ERR | G_IO_HUP):
case G_IO_HUP:
g_message("Socket error HUP\n");
PortClose();
goto error;
case (G_IO_ERR | G_IO_NVAL):
case (G_IO_NVAL):
g_message("Socket error NVAL\n");
goto error;
/* Check for data to be read (or if the socket was closed) */
case G_IO_IN:
Input_Length = g_socket_receive(source, (gchar
*)Receive_Buffer,1024,NULL,NULL);
if (Input_Length != -1)
{
/* Update GUI according to the received data */
MyGuiUpdate(Receive_Buffer,Input_Length);
}
break;
default:
;
} /* condition */
/* Returns TRUE so it remains installed until we remove it */
return TRUE;
error:
return FALSE;
}
void SocketClose(void)
{
g_socket_close(mySocket,NULL);
g_object_unref(mySocketConnection);
g_object_unref(mySocketClient);
g_source_unref(mySource);
}
Any comments about how to improve, missing code, etc.?
I'm now working on the server side and post the result here for convenience.
Thanks,
JP
[
Date Prev][
Date Next] [
Thread Prev][
Thread Next]
[
Thread Index]
[
Date Index]
[
Author Index]