1 /* This is a simple TCP server that listens on port 1234 and provides lists
2 * of files to clients, using a protocol defined in file_server.proto.
4 * It directly deserializes and serializes messages from network, minimizing
7 * For flexibility, this example is implemented using posix api.
8 * In a real embedded system you would typically use some other kind of
9 * a communication and filesystem layer.
12 #include <sys/socket.h>
13 #include <sys/types.h>
14 #include <netinet/in.h>
20 #include <pb_encode.h>
21 #include <pb_decode.h>
23 #include "fileproto.pb.h"
26 bool listdir_callback(pb_ostream_t *stream, const pb_field_t *field, void * const *arg)
28 DIR *dir = (DIR*) *arg;
32 while ((file = readdir(dir)) != NULL)
34 fileinfo.inode = file->d_ino;
35 strncpy(fileinfo.name, file->d_name, sizeof(fileinfo.name));
36 fileinfo.name[sizeof(fileinfo.name) - 1] = '\0';
38 if (!pb_encode_tag_for_field(stream, field))
41 if (!pb_encode_submessage(stream, FileInfo_fields, &fileinfo))
48 void handle_connection(int connfd)
50 ListFilesRequest request;
51 ListFilesResponse response;
52 pb_istream_t input = pb_istream_from_socket(connfd);
53 pb_ostream_t output = pb_ostream_from_socket(connfd);
56 if (!pb_decode(&input, ListFilesRequest_fields, &request))
58 printf("Decode failed: %s\n", PB_GET_ERROR(&input));
62 directory = opendir(request.path);
64 printf("Listing directory: %s\n", request.path);
66 if (directory == NULL)
70 response.has_path_error = true;
71 response.path_error = true;
72 response.file.funcs.encode = NULL;
76 response.has_path_error = false;
77 response.file.funcs.encode = &listdir_callback;
78 response.file.arg = directory;
81 if (!pb_encode(&output, ListFilesResponse_fields, &response))
83 printf("Encoding failed.\n");
87 int main(int argc, char **argv)
90 struct sockaddr_in servaddr;
93 listenfd = socket(AF_INET, SOCK_STREAM, 0);
95 setsockopt(listenfd, SOL_SOCKET, SO_REUSEADDR, &reuse, sizeof(reuse));
97 memset(&servaddr, 0, sizeof(servaddr));
98 servaddr.sin_family = AF_INET;
99 servaddr.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
100 servaddr.sin_port = htons(1234);
101 if (bind(listenfd, (struct sockaddr*)&servaddr, sizeof(servaddr)) != 0)
107 if (listen(listenfd, 5) != 0)
115 connfd = accept(listenfd, NULL, NULL);
123 printf("Got connection.\n");
125 handle_connection(connfd);
127 printf("Closing connection.\n");