// SocketSimpleServer.cpp : Defines the entry point for the console application.
//

#include "stdafx.h"
#include <stdio.h>
#include <winsock.h>
#pragma comment(lib, "wsock32.lib")

void StreamServer(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;
    int nRet;
	char Port[256];
    short nPort;
	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;
    }
    StreamServer(nPort);
    WSACleanup();
}
void StreamServer(short nPort)
{
	char szBuf[256];
    SOCKET listenSocket;
    listenSocket = socket(AF_INET,SOCK_STREAM,IPPROTO_TCP);
	if (listenSocket == INVALID_SOCKET)
		{
        PRINTERROR("socket()");
        return;
		}
	SOCKADDR_IN saServer;
    saServer.sin_family = AF_INET;
    saServer.sin_addr.s_addr = INADDR_ANY;
    saServer.sin_port = htons(nPort);
	int nRet;
	nRet = bind(listenSocket,(LPSOCKADDR)&saServer, sizeof(struct sockaddr));
    if (nRet == SOCKET_ERROR)
		{
         PRINTERROR("bind()");
         closesocket(listenSocket);
         return;
		}

    int nLen;
    nLen = sizeof(SOCKADDR);
    

    nRet = gethostname(szBuf, sizeof(szBuf));
    if (nRet == SOCKET_ERROR)
		{
         PRINTERROR("gethostname()");
         closesocket(listenSocket);
         return;
		}

    printf("\nServer named %s waiting on port %d\n", szBuf, nPort);
    printf("\nlisten()");
	nRet = listen(listenSocket, SOMAXCONN);
    if (nRet == SOCKET_ERROR)
		{
         PRINTERROR("listen()");
         closesocket(listenSocket);
         return;
		}
	SOCKET remoteSocket;
	remoteSocket = accept(listenSocket, NULL, NULL);
	if (remoteSocket == INVALID_SOCKET)
		{
         PRINTERROR("accept()");
         closesocket(listenSocket);
         return;
		}
	
	while(1)
	{
     memset(szBuf, 0, sizeof(szBuf));
     nRet = recv(remoteSocket, szBuf,sizeof(szBuf),0);
    if (nRet == INVALID_SOCKET)
		{
         PRINTERROR("recv()");
         closesocket(listenSocket);
         closesocket(remoteSocket);
         return;
		}
	printf("\nMessage received: %s", szBuf);
    	
    memset(szBuf, 0, sizeof(szBuf));
    printf("\nVvedite soobshenie: ");
	gets(szBuf);
	nRet = send(remoteSocket, szBuf, strlen(szBuf),0);
	}
    closesocket(remoteSocket);
    closesocket(listenSocket);
    return;
}
