#include<stdio.h>
#include<stdlib.h>
#include<unistd.h>
#include<string.h>
#include<sys/types.h>
#include<sys/socket.h>
#include<arpa/inet.h>
#include<pthread.h>
#define BUFF_SIZE 1024
void gotoxy(int x,int y)
{
printf("\033[%d;%df",y,x);
//터미널 출력 위치 변경 함수, y값이 화면 길이보다 크면 화면 길이로 처리된다.(버그의 원인)
fflush(stdout);
}
int client_socket;
int check;
void* rcv_thread(void *data)
{
int i;
char buff_rcv[BUFF_SIZE+5];
int rcv;
while(1)
{
rcv=recv(client_socket, buff_rcv, BUFF_SIZE, 0);
if(rcv>0)
{
while(check==1);
check=2;
for(i=0;i<rcv;)
{
gotoxy(0,100);//gotoxy의 특징을 이용하여 화면을 한칸 올린다.
printf("\n");
gotoxy(0,14);
printf(" ");
gotoxy(0,14);
printf("%s",&buff_rcv[i]);
i+=strlen(&buff_rcv[i])+1;
}
}
else
{
printf("disconnected\n");
break;
}
gotoxy(0,15);
printf("write message to send : ");
gotoxy(25,15);
check=0;
}
}
void* snd_thread(void *data)
{
char buff_snd[BUFF_SIZE+5];
while(1)
{
while(check==2);
check=1;
gotoxy(0,15);
printf("write message to send : ");
gotoxy(25,15);
check=0;
fgets(buff_snd,BUFF_SIZE,stdin);
check=0;
if(send(client_socket, buff_snd, strlen(buff_snd)+1,0)<=0)
{
printf("disconnected\n");
break;
}
}
}
int main()
{
struct sockaddr_in server_addr;
char buff_snd[BUFF_SIZE+5];
char buff_rcv[BUFF_SIZE+5];
int rcv;
int i;
pthread_t p_thread[2];
client_socket=socket(PF_INET, SOCK_STREAM, 0);
if(client_socket==-1)
{
printf("socket error\n");
return 1;
}
memset( &server_addr, 0, sizeof( server_addr));
server_addr.sin_family = AF_INET;
server_addr.sin_port = htons( 4000);
server_addr.sin_addr.s_addr= inet_addr( "127.0.0.1");
if(-1==connect(client_socket,(struct sockaddr*)&server_addr, sizeof( server_addr) ) )
{
printf("connect error\n");
return 1;
}
sprintf(buff_snd,"test\n");
send(client_socket, buff_snd, strlen(buff_snd)+1,0);
recv(client_socket, buff_rcv,BUFF_SIZE,0);
printf("%s\n",buff_rcv);
printf("connecting succesed\n");
memset(&p_thread[0],0,sizeof(p_thread[0]));
pthread_create(&p_thread[0],NULL,rcv_thread,(void *)NULL);
memset(&p_thread[1],0,sizeof(p_thread[1]));
pthread_create(&p_thread[1],NULL,snd_thread,(void *)NULL);
pthread_join(p_thread[0],(void**)&rcv);
pthread_join(p_thread[1],(void**)&rcv);
/*
while(1)
{
printf("write message to send : ");
fgets(buff_snd,BUFF_SIZE,stdin);
if(send(client_socket, buff_snd, strlen(buff_snd)+1,0)<0)
{
printf("disconnected\n");
break;
}
printf("sended\n\n");
while(1)
{
rcv=recv(client_socket, buff_rcv, BUFF_SIZE, 0);
if(rcv>0)
{
for(i=0;i<rcv;)
{
printf("%s",&buff_rcv[i]);
i+=strlen(&buff_rcv[i])+1;
}
break;
}
else
{
printf("disconnected\n");
break;
}
}
if(rcv<=0)
break;
}
//*/
close(client_socket);
return 0;
}