/*
 *	sock_ex_servidor.c
 *	exemplo de servidor de rotinas de comunicacoes usando sockets
 *
 *  98.03.24
 *
 */

/*
============================== C O P Y R I G H T ==============================

(C) 1995-98 Paulo Sousa

This software was written by Paulo Sousa, Researcher of Instituto Superior de 
Engenharia do Porto (ISEP/IPP), Portugal. Use of this software, for any 
purpose, is granted subject to the following conditions: 

1.	This copyright notice must be included with the software or any software
	derived from it;

2.	The risk of using this software is accepted by the user. No warranty as to
	its usefulness or functionality is provided or implied. ISEP provides no 
	support;

3.	You may redistribute this and other files or routines as long as you are
	not compensated for it. You may not use the released source codes in anyway
	commercial without permission.

It'd be nice if you share your modifications with me and everyone else.
email:	psousa@dei.isep.ipp.pt
WWW:	http://www.dei.isep.ipp.pt/~psousa

===============================================================================
*/

/*
 * antes de compilar copiar macros apropriadas
 *
#define TP_OS_WINDOWS
#define TP_OSVER_WIN32
#define TP_OS_OS400
#define TP_HWD_ALPHA
 *
 */

/* compilacao para Win95/NT em maquina Intel */
#define TP_OS_WINDOWS
#define TP_OSVER_WIN32


#include "tc_sock.h"


main(int argc, char* argv[])
{
SOCKET s;
char service[255];
char msg[255];
char buffer_msg[255 + sizeof(short)];
char buffer_dest[255 + sizeof(short)];
short ctlen, msg_len;
short r_ctlen, r_msg_len;
short r;

	if (argc < 2)
	{
		puts("usage: sock_ex_servidor service mensagem\n");
		puts("       service - nome de servico ou port number\n");
		exit(1);
	}

	/* inicializar variaveis */
	strncpy(service, argv[2], sizeof(service)-1);
	service[sizeof(service)-1] = '\0';

	strncpy(msg, argv[3], sizeof(msg)-1);
	msg[sizeof(msg)-1] = '\0';

	/*
	 * aqui e' que comeca o exemplo propriamente dito
	 */

	/* inicializacoes */
	if (!sock_startup())
	{
		puts("erro ao inicializar comunicacoes\n");
		exit(2);
	}

	/* criar socket e esperar por clientes */
	srv_sock = sock_create_stream(service);
	if (srv_sock == SOCKET_ERROR)
	{
		puts("erro ao criar o socket\n");
		exit(3);
	}

	s = sock_listen_accept(srv_sock, NULL, NULL);
	if (s == SOCKET_ERROR)
	{
		puts("erro ao aceitar conexao\n");
		exit(3);
	}

	/* receber mensagem do cliente */
	r = sock_recv_n(s, &r_ctlen, sizeof(short));
	if (r == SOCKET_ERROR)
	{
		puts("erro ao receber mensagem");
		exit(6);
	}
	else if (r == 0)
	{
		puts("o cliente fechou a conexao");
		exit(5);
	}

	r_ctlen = ntohs(r_ctlen);	/* ntohs - converte um inteiro de 16 bits da representacao
								 * usada na rede para o formato deste processador 
								 */
	sock_recv_n(s, buffer_dest, r_ct_len);
	if (r == SOCKET_ERROR)
	{
		puts("erro ao receber mensagem");
		exit(6);
	}
	else if (r == 0)
	{
		puts("o servidor fechou a conexao");
		exit(5);
	}

	printf("pedido: %s", buffer_dest);


	/* construir mensagem de resposta */
	ctlen = htons(strlen(msg));	/* htons - converte um inteiro de 16 bits da representacao
								 * usada no processador do programa cliente para o formato
								 * canonico da rede
								 */
	msg_len = strlen(msg)+sizeof(short);
	memcpy(buffer_msg, &ctlen, sizeof(short));
	memcpy(buffer_msg+sizeof(short), msg, strlen(msg));

	/* enviar */
	r = sock_send_n(s, buffer_msg, msg_len);
	if (r == SOCKET_ERROR)
	{
		puts("erro ao enviar mensagem");
		exit(4);
	}
	else if (r == 0)
	{
		puts("o cliente fechou a conexao");
		exit(5);
	}

	/* fechar conexao */
	sock_close(s);

	/* limpar a casa */
	sock_cleanup();
}
