#include <winsock2.h>
#include <windows.h>
#include <stdio.h>
#include <stdlib.h>
#include <conio.h>
#include <iostream>
#include <string>

#pragma comment(lib, "ws2_32.lib")

#define DEFAULT_PORT        5150
#define DEFAULT_BUFFER      64

using namespace std;

int     iPort = DEFAULT_PORT;      // Port

int main(int argc, char **argv)
{
	cout << "Przyklad do kursu WinSock napisanego przez get'a " << endl;
	cout << "== Polaczenie i rozmowa synchroniczna - SERWER ==" << endl;

    WSADATA	wsd;
    SOCKET sListen, sClient;
    int iAddrSize;
    sockaddr_in	local, client;
	int iPort = DEFAULT_PORT;

    if (WSAStartup(MAKEWORD(2,2), &wsd) != 0)
    {
		cout << "Nie mozna stworzyc WinSock'a." << endl;
        return 1;
    }

    // Create server (listen) socket
    sListen = socket(AF_INET, SOCK_STREAM, IPPROTO_IP);
    if (sListen == SOCKET_ERROR)
    {
		cout << "Nie mozna stworzyc gniazda (" << WSAGetLastError() << ")." << endl;
        return 1;
    }

	local.sin_addr.s_addr = htonl(INADDR_ANY);
	local.sin_family = AF_INET;
	local.sin_port = htons((u_short)iPort);

    if (bind(sListen, (sockaddr *)&local, sizeof(local)) == SOCKET_ERROR)
    {
		cout << "Nie mozna przypisac ustawien (" << WSAGetLastError() << ")." << endl;
        return 1;
    }

    listen(sListen, SOMAXCONN);
   
	cout << "Serwer uruchomiony pomyslnie." << endl;

	while ( true )
    {
        iAddrSize = sizeof(client);
        sClient = accept(sListen, (sockaddr *)&client, &iAddrSize);        
        if (sClient == INVALID_SOCKET)
        {        
			cout << "Nie mozna zaakceptowac uzytkownika (" << WSAGetLastError() << ")." << endl;
            return 1;
        }

		cout << "Uzytkownik polaczony: " << inet_ntoa(client.sin_addr) << ":" << ntohs(client.sin_port) << endl;

		char welcome[DEFAULT_BUFFER] = "Witam na przykladowym serwerze!";
		send(sClient, welcome, strlen(welcome)+1, 0);
		cout << "Wyslano: " << welcome << endl;
		recv(sClient, welcome, DEFAULT_BUFFER, 0);
		cout << "Odebrano: " << welcome << endl;

		cout << "Rozlaczam.";
		
		closesocket(sClient);
	}

	closesocket(sListen);
	WSACleanup();

	cout << "Serwer wylaczony." << endl;
}
