NAME
on_message
- is invoked by the gcs
when a message is received from a connection.
SYNOPSIS
#include <game-carrier/server.h>
GC_ADAPTER_EVENT
void on_message(
GCT_INTPTR conn_user,
GCT_PTR data,
GCT_SIZE len);
Parameters:
conn_user
GCT_INTPTR
User data associated with the connection.data
GCT_PTR
Pointer to the message data.len
GCT_SIZE
The length of the message.
RETURN VALUE
None.
DESCRIPTION
The on_message
function is invoked by the gcs
when a message is received
from a connection.
The on_message
function is executed within the worker thread context of the
gcs
. All connection events are serialized, eliminating the need for
synchronization primitives. The connection is not tied to a specific
thread within the worker thread pool, so there is no guarantee that
the same thread will handle all connection events.
The conn_user
parameter represents the user data associated with
the connection, which is the same value returned by the on_connect
call.
The data
parameter is a pointer to the message data. It’s important to note
that the message data will be freed immediately after the on_message
call,
so if the data needs to be preserved, it should be copied.
The len
parameter indicates the length of the message.
EXAMPLE
#include <game-carrier/server.h>
#include <stdlib.h>
#include <string.h>
/* Example of application that stores the last message from a connection */
struct connection_data {
GCT_INTPTR handle;
void * last_message;
/* user data asociated with connection */
};
GC_ADAPTER_EVENT
GCT_INTPTR on_connect(
GCT_INT app_id,
GCT_INTPTR handle,
GCT_INT pid,
GCT_CSTR rip,
GCT_INT rport,
GCT_CSTR lip,
GCT_INT lport,
GCT_CSTR udata)
{
/* Allocate user data */
struct connection_data * conn = malloc(sizeof(struct connection_data));
/*Out of memory, failed */
if (conn == NULL) {
return GC_DROP_CONNECTION;
}
/* Save connection handler */
conn->handle = handle;
/* No last message yet */
conn->last_message = NULL;
/* initialize other fields */
return (GCT_INTPTR)conn;
}
GC_ADAPTER_EVENT
void on_message(
GCT_INTPTR user,
GCT_PTR data,
GCT_SIZE len)
{
struct connection_data * conn = (struct connection_data *)user;
void * msg = realloc(conn->last_message, len);
if (msg == NULL) {
free(conn->last_message);
conn->last_message = NULL;
return;
}
memcpy(msg, data, len);
conn->last_message = msg;
}
GC_ADAPTER_EVENT
void on_disconnect(GCT_INTPTR user)
{
struct connection_data * conn = (struct connection_data *)user;
free(conn->last_message);
}