repo: atende cliente

Cliente:

#include <Windows.h>
#include <tchar.h>
#include <math.h>
#include <stdio.h>
#include <fcntl.h>
#include <io.h>
#include <time.h>
#include "..\cliente\util.h"


int _tmain(int argc, TCHAR* argv[]) {
	HANDLE hPipe;
	TCHAR szStr[TAM];
	DWORD dwLidos, dwEscritos;

#ifdef UNICODE 
	_setmode(_fileno(stdin), _O_WTEXT);
	_setmode(_fileno(stdout), _O_WTEXT);
	_setmode(_fileno(stderr), _O_WTEXT);
#endif

	while (1) {
		//cada vez que um cliente se ligar é criada uma nova thread
		hPipe = CreateFile(NOME_PIPE, 
			GENERIC_READ | GENERIC_WRITE,
			0,
			NULL,
			OPEN_EXISTING,
			0,
			NULL);
		if (hPipe != INVALID_HANDLE_VALUE) {
			break;
			
		}
		WaitNamedPipe(NOME_PIPE, 10000); //espera 10 segundos
	}
	do{
		_tprintf(_T("TEXTO: "));
		if (_fgetts(szStr, TAM, stdin) == NULL) {
			break;
		}
		szStr[_tcslen(szStr) - 1] = _T('\0');
		WriteFile(hPipe, szStr, ((DWORD)_tcslen(szStr) + 1) * sizeof(TCHAR), &dwEscritos, NULL);
		_tprintf(_T("Enviei: %s (%d)\n"), szStr, dwEscritos);
		ReadFile(hPipe, szStr, TAM, &dwLidos, NULL);
		_tprintf(_T("Recebi: %s (%d)\n"), szStr, dwLidos);
	} while (_tcscmp(szStr, _T("SAIR")) != 0);
	return 0;
}

Servidor:

#include <Windows.h>
#include <tchar.h>
#include <math.h>
#include <stdio.h>
#include <fcntl.h>
#include <io.h>
#include <time.h>
#include "..\cliente\util.h"


DWORD WINAPI atendeCliente(LPVOID lpData) {
	HANDLE hPipe = (HANDLE)lpData;
	TCHAR szStr[TAM];
	DWORD dwLidos, dwEscritos;

	_tprintf(_T("Cliente ligado...\n"));
	while (1) {
		if (!ReadFile(hPipe, szStr, TAM, &dwLidos, NULL)) { //lê pedido..
			break;
		}
		_tprintf(_T("Recebi: %s (%d)\n"), szStr, dwLidos); 
		CharUpperBuff(szStr, dwLidos/sizeof(TCHAR)); //processa
		WriteFile(hPipe, szStr, dwLidos, &dwEscritos, NULL); //envia resposta
		_tprintf(_T("Enviei: %s (%d)\n"), szStr, dwEscritos);
	}
	_tprintf(_T("O cliente desligou...\n"));
	FlushFileBuffers(hPipe);
	DisconnectNamedPipe(hPipe);
	CloseHandle(hPipe);
	return 0;
}

int _tmain(int argc, TCHAR* argv[]) {
	HANDLE hPipe;
	DWORD dwTid;

#ifdef UNICODE 
	_setmode(_fileno(stdin), _O_WTEXT);
	_setmode(_fileno(stdout), _O_WTEXT);
	_setmode(_fileno(stderr), _O_WTEXT);
#endif
	
	while (1) {
		//cada vez que um cliente se ligar é criada uma nova thread
		hPipe = CreateNamedPipe(
			NOME_PIPE, 
			PIPE_ACCESS_DUPLEX,
			PIPE_TYPE_MESSAGE | PIPE_READMODE_MESSAGE | PIPE_WAIT, 
			PIPE_UNLIMITED_INSTANCES, 
			BUFFSIZE, 
			BUFFSIZE, 
			10000, 
			NULL);
		if (ConnectNamedPipe(hPipe, NULL)) {
			CreateThread(NULL, 0, atendeCliente, (LPVOID)hPipe, 0, &dwTid);
		}
	}
	return 0;
}

Util:

#define TAM 100
#define NOME_PIPE TEXT("\\\\.\\pipe\\teste")
#define BUFFSIZE 1024
Tags : ,

0 thoughts on “repo: atende cliente”

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.