1 /* This is a simple TCP client that connects to port 1234 and prints a list
2 * of files in a given directory.
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 printfile_callback(pb_istream_t *stream, const pb_field_t *field, void **arg)
30 if (!pb_decode(stream, FileInfo_fields, &fileinfo))
33 printf("%-10lld %s\n", (long long)fileinfo.inode, fileinfo.name);
38 bool listdir(int fd, char *path)
40 ListFilesRequest request;
41 ListFilesResponse response;
42 pb_istream_t input = pb_istream_from_socket(fd);
43 pb_ostream_t output = pb_ostream_from_socket(fd);
48 request.has_path = false;
52 request.has_path = true;
53 if (strlen(path) + 1 > sizeof(request.path))
55 fprintf(stderr, "Too long path.\n");
59 strcpy(request.path, path);
62 if (!pb_encode(&output, ListFilesRequest_fields, &request))
64 fprintf(stderr, "Encoding failed.\n");
68 /* We signal the end of request with a 0 tag. */
69 pb_write(&output, &zero, 1);
71 response.file.funcs.decode = &printfile_callback;
73 if (!pb_decode(&input, ListFilesResponse_fields, &response))
75 fprintf(stderr, "Decode failed: %s\n", PB_GET_ERROR(&input));
79 if (response.path_error)
81 fprintf(stderr, "Server reported error.\n");
88 int main(int argc, char **argv)
91 struct sockaddr_in servaddr;
97 sockfd = socket(AF_INET, SOCK_STREAM, 0);
99 memset(&servaddr, 0, sizeof(servaddr));
100 servaddr.sin_family = AF_INET;
101 servaddr.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
102 servaddr.sin_port = htons(1234);
104 if (connect(sockfd, (struct sockaddr *)&servaddr, sizeof(servaddr)) != 0)
110 if (!listdir(sockfd, path))