쓰레드 이용한 채팅프로그램 질문입니다~
일단 소스 먼저 보여 드릴께요
/*
* echo_server.c
* Written by SW. YOON
*/
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#define BUFSIZE 1024
void error_handling(char *message);
void *thread_accept_t(void *arg);
void *thread_write_t(void *arg);
void *thread_read_t(void *arg);
int serv_sock;
int clnt_sock[10];
char message[BUFSIZE];
int str_len;
struct sockaddr_in serv_addr;
struct sockaddr_in clnt_addr;
int clnt_addr_size;
int count = 0;
int main(void)
{
int i;
char *serv_ip="220.64.218.200";
char *serv_port="9191";
serv_sock=socket(PF_INET, SOCK_STREAM, 0);
if(serv_sock == -1)
error_handling("socket() error");
memset(&serv_addr, 0, sizeof(serv_addr));
serv_addr.sin_family=AF_INET;
serv_addr.sin_addr.s_addr=htons(INADDR_ANY);
serv_addr.sin_port=htons(atoi(serv_port));
if(bind(serv_sock, (struct sockaddr*) &serv_addr, sizeof(serv_addr))==-1)
error_handling("bind() error");
// while(1)
// {
if(listen(serv_sock, 5)==-1)
error_handling("listen() error");
int res1,res2,res3;
pthread_t accept_thread[10];
pthread_t write_thread;
pthread_t read_thread;
void *thread_accept;
void *thread_write;
void *thread_read;
res1 = pthread_create(&(accept_thread[count]), NULL, thread_accept_t, (void *)message);
res1 = pthread_join(accept_thread[count], &thread_accept);
res2 = pthread_create(&write_thread, NULL, thread_write_t, (void *)message);
res3 = pthread_create(&read_thread, NULL, thread_read_t, (void *)message);
res2 = pthread_join(write_thread, &thread_write);
res3 = pthread_join(read_thread, &thread_read);
// if (count >= 10)
// break;
// }
close(serv_sock);
return 0;
}
void error_handling(char *message)
{
fputs(message, stderr);
fputc('\n', stderr);
exit(1);
}
void *thread_write_t(void *arg)
{
while(1)
{
fgets(message, BUFSIZE, stdin);
if(!strcmp(message,"q\n"))
break;
write(clnt_sock[count-1], message, strlen(message));
}
}
void *thread_read_t(void *arg)
{
while(1)
{
read(clnt_sock[count-1], message, BUFSIZE);
printf("\n%s\n", message);
if(!strcmp(message,"q\n"))
break;
}
close(clnt_sock[count-1]);
}
void *thread_accept_t(void *arg)
{
printf("%d\n",count);
clnt_addr_size=sizeof(clnt_addr);
clnt_sock[count] = accept(serv_sock, (struct sockaddr*)&clnt_addr,&clnt_addr_size);
if(clnt_sock[count] == -1)
error_handling("accept() error");
count++;
}
저기에서 쓰레드 부분에서 막히네요 ㅜ.ㅜ 제가 의도한바는 accept하는 쓰레드가 돌고 그다음 read,write하는 쓰레드가
돌고 난 다음 다음 accept하는 쓰레드로 넘어가야 하는데 read,write하는 쓰레드에서 막혀서 빠져나가지를 못하네요ㅜ.ㅜ
소스 읽으시기 짜증 스럽더라도 저 read,write 하는 쓰레드를 어떻게 구현해야 할지 따끔한 충고 부탁드립니다
댓글 달기