#include <WinSock2.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#define MAXLINE 1024
DWORD WINAPI stdin_input_send_thread(LPVOID arg);
char line[MAXLINE], chatdata[MAXLINE+1];
struct sockaddr_in server_addr;
SOCKET clientsocket; //server connect socket
char *escape = "quit"; //exit command message
BOOL bisquit; //exit falg variable
int main(int argc, char *argv[])
{
WSADATA wsa; //socket
HANDLE hthread; //thread
DWORD threadid;
int size;
if (argc != 3)
{
printf("usage : %s server_address port\n", argv[0]);
return(-1);
}
bisquit = FALSE;
//socket initialization
if (WSAStartup(MAKEWORD(2,2), &wsa) != 0)
{
return(-2);
}
//socket creation
if ((clientsocket = socket(AF_INET, SOCK_STREAM, 0)) < 0)
{
printf("fail make socket\n");
return(-3);
}
//memory initialization
memset(&server_addr, 0x00, sizeof(server_addr));
server_addr.sin_family = AF_INET;
server_addr.sin_addr.s_addr = inet_addr(argv[1]);
server_addr.sin_port = htons(atoi(argv[2]));
//connection with server
if (connect(clientsocket, (struct sockaddr *)&server_addr, sizeof(server_addr)) < 0)
{
printf("fail connect to server\n");
return(-4);
}
else
{
printf("connected server\n");
}
//stdin & send data thread creation
//stdin & send data thread creation
//stdin & send data thread creation
//stdin & send data thread creation
//stdin & send data thread creation
hthread = CreateThread(NULL, 0, stdin_input_send_thread, 0, 0, &threadid);
if (hthread == NULL)
{
printf("fail make thread\n");
}
else
{
CloseHandle(hthread);
}
while (!bisquit)
{
memset(chatdata, 0x00, sizeof(chatdata));
if ((size = recv(clientsocket, chatdata, MAXLINE, 0)) == INVALID_SOCKET)
{
break;
}
else
{
chatdata[size] = '\0';
printf("%s", chatdata);
}
}
closesocket(clientsocket);
WSACleanup();
return(0);
}
//user data input mechanism
DWORD WINAPI stdin_input_send_thread(LPVOID arg)
{
while(TRUE)
{
//stream read in stdin, input '\n' character is ended.
//stream read in stdin, input '\n' character is ended.
if (fgets(chatdata, MAXLINE, stdin))
{
chatdata[strlen(chatdata) - 1] = 0x00;
sprintf(line, "%s", chatdata);
if (strstr(line, escape) != 0) //exit command str
{
printf("GoodBye!!!!!!!\n");
closesocket(clientsocket);
bisquit = TRUE;
return(-1);
}
if (send(clientsocket, line, strlen(line), 0) < 0)
{
printf("write fail\n");
return(-2);
}
}
}
return 0;
}
'통신 > SELECT(TCP)' 카테고리의 다른 글
WINDOWS,SERVER,SELECT(FILE RECV),BASIC(SEND) (0) | 2019.10.29 |
---|---|
WINDOWS,CLIENT,THREAD(FILE READ SEND),BASIC(RECV) (0) | 2019.10.29 |
LINUX,SERVER,SELECT(RECV),SELECT(SEND) (0) | 2019.10.29 |
Makefile(win_calc_server: win_calc_server.o pushcall.o common.o calc_server.o) (0) | 2019.10.29 |
Windows,server,tcp,select(recv),select(send),multi-client (0) | 2019.10.29 |