/* imaged.c * Austin Vandergon, 7/21/06 * imaged serves a particular image from the filesystem any time the request * sequence "0110" is received. The image served is created by other threads * doing image composition continuously. */ #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include "imaged.h" int main(int argc, char** argv) { int sockfd, connected_fd; pthread_t tmp,imagecomp; struct sockaddr_in my_addr; // set up some stuff sockfd = socket(PF_INET, SOCK_STREAM, 0); assert(sockfd != -1); // socket returns -1 on error my_addr.sin_family = AF_INET; my_addr.sin_port = htons(PORT); my_addr.sin_addr.s_addr = htons(INADDR_ANY); // this machine memset(&(my_addr.sin_zero), '\0', 8); // zero the rest of the struct // avoid address already in use error int yes=1; if (setsockopt(sockfd, SOL_SOCKET, SO_REUSEADDR, &yes,sizeof(int)) == -1) { perror("setsockopt"); exit(1); } if(bind(sockfd, (struct sockaddr *)&my_addr, sizeof(struct sockaddr)) == -1) perror("binding"); listen(sockfd, 10); // 10 connections in the queue seems good // need the image to be ready to serve pthread_create(&imagecomp, 0, imagecomp_thread, 0); // and last, some server threads while(1) { connected_fd = accept(sockfd, NULL, NULL); // create a new thread to handle the connection pthread_create(&tmp, 0, serve_client, &connected_fd); // detach the thread and let it do its own thing pthread_detach(tmp); } return 0; } /* serve_client waits for the request sequence ("0110") * and upon receving it, sends back a short representing * the filesize, then 0x01, then the image. The connection * is not closed until the client closes it. */ void* serve_client(void* connected_fd) { char tmp[4], im[512]; short filesize, received, junk; struct stat buf; void* image; int fd; junk = htons(1); //image = mmap(0,2*filesize,PROT_READ,MAP_SHARED,fd,0); // mmapping may be a bad idea int sfd = *((int*)connected_fd); printf("Client connected.\n"); while(1) { received = 0; memset(&tmp,0,4); while(received < 4) { received += recv(sfd, (void*)tmp, sizeof(tmp), 0); if(received <= 1) { printf("Client disconnected.\n"); pthread_exit(0); } } if(tmp[0] = '0' && tmp[1] == '1' && tmp[2] == '1' && tmp[3] == '0') { pthread_mutex_lock(&outimage_mutex); fd = open("/ram/image.jpeg",0,O_RDONLY); stat("/ram/image.jpeg",&buf); filesize = htons(buf.st_size); memcpy(tmp, &filesize, 2); memcpy(&tmp[2], &junk, 2); send(sfd, tmp, 4, 0); short b_read, rem, sent = 0; while(sent < buf.st_size) { rem = buf.st_size - sent; b_read = read(fd, im, (rem<512?rem:512)); if((sent += send(sfd, im, (b_read<512?b_read:512), 0)) == -1) { perror("send"); pthread_exit(0); } } close(fd); pthread_mutex_unlock(&outimage_mutex); } } return NULL; }