#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      4096

using namespace std;

struct ExampleData
{
	char text[32];
	unsigned int number;
};

int     iPort = DEFAULT_PORT;      // Port

int main(int argc, char **argv)
{
	cout << "Przyklad do kursu WinSock napisanego przez get'a " << endl;
	cout << "== WYSYLANIE STRUKTUR - 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;

		// zwykła struktura
		ExampleData example;
		strcpy(example.text, "Example text");
		example.number = 1771;
		char *toSend = reinterpret_cast<char*>(&example);
		send(sClient, toSend, sizeof(example), 0);

		cout << "Rozlaczam.";
		
		closesocket(sClient);
	}

	closesocket(sListen);
	WSACleanup();

	cout << "Serwer wylaczony." << endl;
	getch();
	return 0;
}
