Estratto del documento

#include <stdio.h>

#include <string.h>

#include <winsock.h>

#define PORT 6644

#define VITTORIA "Complimenti hai vinto !!XD\0"

#define SCONFITTA "Complimenti hai PERSO !!XD\0"

#define MAX_STRING 256

void client(char *);

void error(char *);

int InitializeWinsock(WORD );

void Usage();

int main(int argc, char *argv[]) {

if ( argc < 2 ) Usage();

if (!InitializeWinsock (MAKEWORD(1,1) ) ) return 1;

client(argv[1]);

WSACleanup();

return 0;

}

void client(char * server_IP) {

SOCKET fd; // "file" descriptor for the network socket

SOCKADDR_IN saddr;

char buf[MAX_STRING];

if ((fd=socket(AF_INET,SOCK_STREAM,0)) == INVALID_SOCKET)

error("Client: socket not connected ");

saddr.sin_family = AF_INET;

saddr.sin_addr.s_addr = inet_addr(server_IP);

saddr.sin_port = htons(PORT);

// request connection to server socket (remote machine)

if (connect(fd, (LPSOCKADDR) &saddr, sizeof(saddr)) == SOCKET_ERROR)

error("Client: connect ");

//Riceviamo il messaggio di benvenuto

if ( recv(fd, buf, sizeof(buf), 0) == SOCKET_ERROR )

error("Client: receiving failure ");

printf("%s\n",buf);

while (1) {

//ricevo dal server il numero del tentativo

if ( recv(fd, buf, sizeof(buf), 0) == SOCKET_ERROR )

error("Client: receiving failure ");

printf("%s\n",buf);

//dobbiamo uscire se il buf contiene il messaggio di vittoria o

sconfitta esco

if (strstr(buf,VITTORIA)||strstr(buf,SCONFITTA))

break;

//leggo il tentativo

scanf("%s",buf);

//invio il tentativo al server.

if ( send(fd,buf, strlen(buf)+1, 0) == SOCKET_ERROR )

error("Client: sending failure ");

//ricevo la risposta

if ( recv(fd, buf, sizeof(buf), 0) == SOCKET_ERROR )

error("Client: receiving failure ");

printf("%s\n",buf);

}

if (closesocket(fd) == SOCKET_ERROR)

error("Client: closing socket ");

getchar();

}

/**********************************************

* Windows Sockets Initialization *

**********************************************/

int InitializeWinsock(WORD wVersionRequested) {

WSADATA wsaData;

int err;

err = WSAStartup(wVersionRequested, &wsaData);

// ritorna errore se, ad esempio, l'applicazione supporta al massimo

// la versione 1.1 e la DLL supporta da 2.0 in su (le versioni non si

sovrappongono)

if (err!=0) return 0; // Tell the user that we couldn't find a usable

winsock.dll

// WSAStartup returns in wHighVersion (struct wsaData) the highest version

it supports

Anteprima
Vedrai una selezione di 1 pagina su 4
MisterMind esempio Client Pag. 1
1 su 4
Sintesi

Classico gioco del Mastermind fatto in C++: ottimo esempio per vedere la comunicazione di un client con un server.

D/illustrazione/soddisfatti o rimborsati
Acquista con carta o PayPal
Scarica i documenti tutte le volte che vuoi