wcap_bod.c 2.8 KB
#include <stdio.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <signal.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>

#define Port 23
#define BUF_SIZE 1024
int newSockfd, Sockfd;

void Receivedone(int signum)
{
	close(Sockfd);
	close(newSockfd);
	printf("\nconnect done\n");

	exit(0);
}

void send_result(int newsfd) {
	FILE* image;
	int read_size;
	char sync = '\0', msg_buf[BUF_SIZE], file_name[256];
	unsigned int fsize;
	static int ind = 0;
	
	sprintf(file_name, "img_%3d_result.jpg", ind);
	while((image = fopen(file_name,"r")) == NULL) {sleep(1);}
	
	///// file size 
	fseek(image, 0, SEEK_END); 
	fsize = ftell(image); 
	fseek(image, 0, SEEK_SET);
	sprintf(msg_buf,"%d", fsize); 
    	if(write(newsfd, (char*)&msg_buf, sizeof(msg_buf)-1) < 0) { 
     		perror("write");
		exit(1);
	}
	
	printf("Sent picture : %dsize\n", fsize);
	// send image file
	
	while(!feof(image)) { 
		memset(msg_buf, 0, BUF_SIZE);
     		read_size = fread(msg_buf, 1, sizeof(msg_buf), image); // get image file
    		if(write(newsfd, (char*)&msg_buf, read_size) < 0) { // send image file
    	 		perror("write");
			exit(1);
		}
		read(newsfd, (char*)&sync, sizeof(sync)); // for sync	
	}

	if(read(newsfd, (char*)&msg_buf, sizeof(msg_buf)) < 0) { 
		perror("read");
		exit(1);
	} // 종료 확인
	
    bzero(msg_buf, sizeof(msg_buf));
    fclose(image);
	ind++;
	if(ind == 999) ind = 0;
}

int main(int argc, char* argv[])
{
	int hostAddrLen, n, option;
	struct sockaddr_in hostAddr, boardAddr;
	char cwd[256];
	pid_t pid;

	if((pid = fork()) < 0) { // error
		perror("fork");
		exit(1);
	}
	else if (pid > 0) { // only do parent process
		signal(SIGINT, Receivedone); // 종료 signal

		if((Sockfd = socket(PF_INET, SOCK_STREAM, 0)) < 0) {
			perror("socket");
			exit(1);
		}
		option = 1;          // SO_REUSEADDR 의 옵션 값을 TRUE 로
		setsockopt(Sockfd, SOL_SOCKET, SO_REUSEADDR, &option, sizeof(option)); // set socket reusable
		
		bzero((char*)&boardAddr, sizeof(boardAddr));
		boardAddr.sin_family = PF_INET;
		boardAddr.sin_addr.s_addr = htonl(INADDR_ANY);
		boardAddr.sin_port = htons(Port);
	
		if(bind(Sockfd, (struct sockaddr*)&boardAddr, sizeof(boardAddr)) < 0) {
			perror("bind");
			exit(1);
		}

		listen(Sockfd, 5);
	
		printf("\nWait connecting\n\n");

		hostAddrLen = sizeof(hostAddr);

		newSockfd = accept(Sockfd, (struct sockaddr*)&hostAddr,(socklen_t*)&hostAddrLen);
		if(newSockfd < 0) {
			perror("accept");
			exit(1);
		} // === 연결 완료

		if((n = read(newSockfd, (char*)&cwd, sizeof(cwd))) < 0) { // 
			perror("read");
			exit(1);
		} // host cwd 받아오기
	
		// 전송 시작
	}	
	while(1) {
		if(pid == 0) { // do yolo

		}
		send_result(newSockfd);	
		printf("\nSuccess\n=========================================================\n\n");
	}
	return 0;
}