diff options
| -rw-r--r-- | src/net.c | 100 | ||||
| -rw-r--r-- | src/net.h | 3 |
2 files changed, 103 insertions, 0 deletions
@@ -107,6 +107,27 @@ int* server_get_players(int serversock, const uint8_t count) } /** + * Client side function; Send hello to server + * @param[in] sock Socket to use + * @param[in] username Username of player + */ +void client_hello(int sock, const char* username) +{ + uint8_t* buf; + uint8_t namelen = strlen(username); + + buf = malloc(namelen+2); // type + len + username + + buf[0] = CLIENT_HELLO; + buf[1] = namelen; + memcpy(buf+2, username, namelen); + + send(sock, buf, namelen+2, 0); + + free(buf); +} + +/** * Client side function; connects to specified host:port * @param[in] host Hostname of server * @param[in] port Port of server @@ -155,3 +176,82 @@ int client_connect_server(const char* host, const char* port) } +void server_start_game(int* clients, const uint8_t clientcount, const char* usernames[]) +{ + uint8_t* buf; + uint8_t usercount = clientcount + 1; // 1 more user (server) than clients + uint32_t pos = 0; + uint32_t buflen = 2 + usercount; // type + usercount + (usercount * len) + + for(int i=0; i<usercount; i++) + buflen += strlen(usernames[i]); + + buf = malloc(buflen); + buf[pos++] = SERVER_START_GAME; + buf[pos++] = clientcount; + // copy usernames with length to buffer + for(int i=0; i<usercount; i++) + { + uint8_t len = strlen(usernames[i]); + buf[pos++] = len; + memcpy(buf+pos, usernames[i], len); + pos += len; + } + + // send to all users + for(int i=0; i<clientcount; i++) + send(clients[i], buf, buflen, 0); + + free(buf); +} + +/** + * Server side function; receive hello message from client and read username + * @param[in] sock Socket to use + * @return Username of client + */ +char* server_recv_hello(int sock) +{ + char buf[12], *name; + uint8_t namelen; + + recv(sock, buf, 13, 0); + + assert(buf[0] == CLIENT_HELLO); + + namelen = buf[1]; + name = malloc(namelen+1); + strncpy(name, buf+2, namelen); + name[namelen] = '\0'; + + return name; +} + +/** + * Server side function; calls correct handler for incoming packet + * @param[in] sock Socket to use + * @param[in] wanted Packet type that should be handled + * @return Pointer to desired data or NULL if not in recv queue + */ +void* server_recv(int sock, uint8_t wanted) +{ + void* result = NULL; + uint8_t buf[10], type; + ssize_t len = recv(sock, buf, 10, MSG_PEEK); // just peek into packet to determine type + + assert(len != -1); + + type = buf[0]; + if(type != wanted) + return NULL; + + switch(type) + { + case CLIENT_HELLO: + result = server_recv_hello(sock); + break; + } + + return result; +} + @@ -3,6 +3,9 @@ #define MAX_PLAYERS 10 +enum packet_type { CLIENT_HELLO, SERVER_START_GAME }; + + typedef enum { // Specify message type identifier here |
