65 lines
		
	
	
	
		
			1.5 KiB
		
	
	
	
		
			C
		
	
	
	
	
	
		
		
			
		
	
	
			65 lines
		
	
	
	
		
			1.5 KiB
		
	
	
	
		
			C
		
	
	
	
	
	
|  | #include <stdio.h>
 | ||
|  | #include <stdlib.h>
 | ||
|  | 
 | ||
|  | #include <skipstone/link.h>
 | ||
|  | #include <skipstone/map.h>
 | ||
|  | #include <skipstone/queue.h>
 | ||
|  | #include <skipstone/message.h>
 | ||
|  | 
 | ||
|  | struct endpoint { | ||
|  |     uint16_t id; | ||
|  |     skipstone_message_handler *handler; | ||
|  |     void *context; | ||
|  | }; | ||
|  | 
 | ||
|  | struct _skipstone_message_service { | ||
|  |     skipstone_map *endpoints; | ||
|  |     skipstone_queue *pending; | ||
|  | }; | ||
|  | 
 | ||
|  | skipstone_message_service *skipstone_message_service_new() { | ||
|  |     return (skipstone_message_service *)skipstone_map_new(); | ||
|  | } | ||
|  | 
 | ||
|  | int skipstone_message_service_register(skipstone_message_service *service, | ||
|  |         uint16_t id, skipstone_message_handler *handler, void *context) { | ||
|  |     struct endpoint *endpoint; | ||
|  | 
 | ||
|  |     if ((endpoint = malloc(sizeof(*endpoint))) == NULL) { | ||
|  |         goto error_malloc_endpoint; | ||
|  |     } | ||
|  | 
 | ||
|  |     endpoint->id      = id; | ||
|  |     endpoint->handler = handler; | ||
|  |     endpoint->context = context; | ||
|  | 
 | ||
|  |     return skipstone_map_set(service->endpoints, id, endpoint); | ||
|  | 
 | ||
|  | error_malloc_endpoint: | ||
|  |     return -1; | ||
|  | } | ||
|  | 
 | ||
|  | int skipstone_message_service_deregister(skipstone_message_service *service, uint16_t id) { | ||
|  |     return skipstone_map_set((skipstone_map *)service, id, NULL); | ||
|  | } | ||
|  | 
 | ||
|  | int skipstone_message_service_run(skipstone_message_service *service, | ||
|  |         skipstone_link *link) { | ||
|  |     void *buf; | ||
|  |     uint16_t len, id; | ||
|  | 
 | ||
|  |     if ((buf = malloc(SKIPSTONE_MESSAGE_MAX_PAYLOAD)) == NULL) { | ||
|  |         goto error_malloc_buf; | ||
|  |     } | ||
|  | 
 | ||
|  |     while (skipstone_link_recv(link, buf, &len, &id) >= 0) { | ||
|  |         printf("Received message %hu bytes for endpoint %hu\n", | ||
|  |             len, id); | ||
|  |     } | ||
|  | 
 | ||
|  |     return 0; | ||
|  | 
 | ||
|  | error_malloc_buf: | ||
|  |     return -1; | ||
|  | } |