summaryrefslogtreecommitdiff
path: root/src/net.c
blob: d7222e1b9f77502ea8dd06088becd71468910564 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
#include <sys/types.h>
#include <sys/socket.h>
#include <stdlib.h>
#include <stdio.h>
#include <assert.h>
#include "net.h"

void* net_recv(int sock, msg_type_t wanted)
{
	void* result = NULL;
	uint8_t peekbuf[2], type, payload_len, *packet, *payload;
	ssize_t len = recv(sock, peekbuf, 2, MSG_PEEK); // just peek into packet to determine type

	assert(len != -1);

	type = peekbuf[NET_MSG_OFFSET_TYPE];
	payload_len = peekbuf[NET_MSG_OFFSET_PAYLOAD_LENGTH];

	if(type != wanted)
	{
		printf("client_recv: received type %d instead of %d", type, wanted);
		return NULL;
	}

	packet = malloc(payload_len+NET_MSG_OFFSET_PAYLOAD);
	recv(sock, packet, payload_len+NET_MSG_OFFSET_PAYLOAD, 0);
	payload = &packet[NET_MSG_OFFSET_PAYLOAD];

	switch(type)
	{
		case msg_type_hello:
			result = server_recv_hello(payload, payload_len);
			break;
		case msg_type_start_game:
			result = client_recv_player_list(payload, payload_len);
			break;
		case msg_type_deal_cards:
			result = client_recv_deal_cards(payload, payload_len);
			break;
	}
	free(packet);

	return result;
}