cobble/src/connection.c

65 lines
1.4 KiB
C

#include <stdio.h>
#include <pthread.h>
#include <log/log.h>
#include <cobble/connection.h>
#include <cobble/packet.h>
#include <cobble/protocol.h>
#include <cobble/server.h>
#include <cobble/util.h>
#include <../config.h>
// called when a connection receives data
static void
connection_on_data(dyad_Event *e)
{
// variables
Connection *conn;
Packet *packet;
size_t len_size;
int len;
conn = (Connection*) e->udata;
len_size = read_varint(&len, e->data, e->size);
if (len_size == 0 || e->size < len) {
// if this is reached, we didn't get the full packet from the client
// TODO: handle this
return;
}
packet = SAFE_MALLOC(sizeof(Packet));
packet_read(conn, packet, e->data + len_size, len);
packet_handle(conn, packet);
packet_destroy(packet);
}
// called when the server gets a new connection
static void
server_on_accept(dyad_Event *e)
{
// create the connection struct
Connection *conn = SAFE_MALLOC(sizeof(conn));
conn->dyad_stream = e->remote;
conn->protocol_state = HANDSHAKE;
dyad_addListener(e->remote, DYAD_EVENT_DATA, connection_on_data, conn);
log_debug("Got a connection");
}
void
connection_thread(void *args)
{
Server *server = (Server*) args;
dyad_addListener(server->dyad_stream, DYAD_EVENT_ACCEPT, server_on_accept, NULL);
/* TODO make the backlog count (last arg) configurable or something */
dyad_listenEx(server->dyad_stream, SERVER_IP, SERVER_PORT, 128);
// main dyad loop
while (1) {
dyad_update();
}
}