// SocketClient.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include <stdio.h>
#include <winsock.h>
#pragma comment(lib, "wsock32.lib")
void StreamClient(char *szServer, short nPort);
#define PRINTERROR(s) fprintf(stderr,"\n%: %d\n", s, WSAGetLastError())
void main(int argc, char **argv)
{
    WORD wVersionRequested = MAKEWORD(1,1);
    WSADATA wsaData;
	char ServName [256]; 
	char Port [256];
    int nRet;
    short nPort;
	printf("\nVvedite imya servera:  ");
	gets(ServName);
   //  printf("\n %s ", ServName);  
		printf("\nVvedite nomer porta:  ");
	gets(Port);
   // printf("\n %s ", Port);
    nPort = atoi(Port);
    nRet = WSAStartup(wVersionRequested, &wsaData);
    if (wsaData.wVersion != wVersionRequested)
    {
       fprintf(stderr,"\n Wrong version\n");
       return;
    }
    StreamClient(ServName, nPort);
    WSACleanup();
}

void StreamClient(char *szServer, short nPort)
{
	char szBuf[256];
    printf("\nStream Client connecting to server: %s on port: %d", szServer, nPort);
    LPHOSTENT lpHostEntry;
    lpHostEntry = gethostbyname(szServer);
    
	if (lpHostEntry == NULL)
		{
         PRINTERROR("gethostbyname()");
         return;
		}
    
	SOCKET theSocket;
    
	theSocket = socket(AF_INET,
                       SOCK_STREAM,
                       IPPROTO_TCP);
    if (theSocket == INVALID_SOCKET)
		{
         PRINTERROR("socket()");
         return;
		} 
    SOCKADDR_IN saServer;
    saServer.sin_family = AF_INET;
    saServer.sin_addr = *((LPIN_ADDR)*lpHostEntry->h_addr_list);
    saServer.sin_port = htons(nPort);
    
	int nRet;
    nRet = connect(theSocket,(LPSOCKADDR)&saServer,sizeof(struct sockaddr));
    if (nRet == SOCKET_ERROR)
		{
         PRINTERROR("socket()");
         closesocket(theSocket);
         return;
		}
	while(1)
	{
	memset(szBuf, 0, sizeof(szBuf));
    printf("\nVvedite soobshenie, ili 'exit' dlya vihoda: ");
	gets(szBuf);
	if(strcmp(szBuf, "exit")==0)
		{closesocket(theSocket); return;}
	nRet = send(theSocket,szBuf,strlen(szBuf),  0);
    
	if (nRet == SOCKET_ERROR)
		{
         PRINTERROR("send()");
         closesocket(theSocket);
         return;
		}
	nRet = recv(theSocket, szBuf, sizeof(szBuf), 0);
	if (nRet == SOCKET_ERROR)
		{
         PRINTERROR("recv()");
         closesocket(theSocket);
         return;
		}
	printf("\nMessage received: %s", szBuf);
	}
    closesocket(theSocket);
    return;
}
