L'errore è che non funziona la parte client nel cmd
Comunque questo è il codice:
#include <windows.h>
#include <cstdlib>
#include <iostream>
#include<time.h>
#include <winsock2.h>
#include<string>
#define PORT 80
#define MAX_STRING 256
using namespace std;
void client(char *);
void server();
void error(char *);
int InitializeWinsock(WORD );
void Usage();
int main(int argc, char *argv[])
{ srand(time(NULL));
if ( argc < 2 ) Usage();
if (strcmp(argv[1], "client") == 0 )
{
// initialize wsock32.dll, requesting winsock 1.1
if (argc!=3 ) Usage();
if (!InitializeWinsock (MAKEWORD(1,1) ) ) return 1;
client(argv[2]);
WSACleanup();
}
else
if (strcmp(argv[1], "server") == 0 )
{
if (!InitializeWinsock (MAKEWORD(1,1) ) ) return 1;
server();
WSACleanup();
}
else Usage();
return 0;
}
void server ()
{
SOCKET fd, fd_new; // "file" descriptors for the network sockets
SOCKADDR_IN saddr_me;
char buf[MAX_STRING];
string frase[5]={"pino","luca","gino","struzzo","albero"};
char scelta[7];
int x,n; char lettera[2];
int tentativi=5;
char k[3];;
int w;
if ((fd=socket(AF_INET,SOCK_STREAM,0)) == INVALID_SOCKET)
error("Server: socket not connected ");
saddr_me.sin_family = AF_INET;
saddr_me.sin_addr.s_addr= htonl(INADDR_ANY);
saddr_me.sin_port = htons(PORT);
if (bind(fd, (LPSOCKADDR) &saddr_me, sizeof(saddr_me)) == SOCKET_ERROR)
error("Server: bind failure ");
if (listen(fd,1) == SOCKET_ERROR)
error("Server: listen failure ");
printf("\nServer in azione\n");
if ( (fd_new=accept(fd, NULL, NULL)) == INVALID_SOCKET)
error("Server: accept failure ");
// In Windows i sockets non sono dei normali file descriptors, quindi
// non possono essere usate le normali primitive "read" e "write"
strcpy(buf,"Benvenuto al gioco dell'impiccato!");
////invia al client messaggio di benvenuto///
if( send(fd_new, buf, strlen(buf)+1, 0) == SOCKET_ERROR )
error("Server: sending failure ");
x=rand()%5;
n=sizeof(frase[x]);
int z=0;
bool vet[n];
do{
vet[z]=false;
z++;
}while(z<n);
for(int i=0;i<n;i++)
scelta=frase[x];
z=0;
do{
strcat(buf,"_");
z++;
}while(z<n);
/////invia al client i trattini della parola misteriosa///
if( send(fd_new, buf, strlen(buf)+1, 0) == SOCKET_ERROR )
error("Server: sending failure ");
strcpy(buf,"inserisci carattere");
////invia al client inserisci carattere
if( send(fd_new, buf, strlen(buf)+1, 0) == SOCKET_ERROR )
error("Server: sending failure ");
do{
strcpy(k,"no"); ///riceve dal client la lettera///
if( recv(fd_new, lettera, sizeof(lettera), 0) == SOCKET_ERROR )
error("Server: receiving failure ");
for(int i=0;i<n;i++)
{
if(lettera[0]==scelta)
{vet=true;
buf=scelta;
strcpy(k,"ok\0");
}
if(strcmp(k,"no")==0)
{ tentativi-=1;
strcpy(buf,"lettera non presenta nella parola misteriosa, il numero di tentativi rimasti sono");
}
/////invio al client che ha scannato ///
if( send(fd_new, buf, strlen(buf)+1, 0) == SOCKET_ERROR )
error("Server: sending failure ");
char num[2];
itoa(tentativi,num,10);
num[1]='\0';
//////invio al client numeri tentativi rimasti///
if( send(fd_new, num, strlen(num)+1, 0) == SOCKET_ERROR )
error("Server: sending failure ");
w=0;
for(i=0;i<n;i++)
{
if(vet==true)
{ w+=1;
char x[2];
x[0]=scelta;
strcat(buf,x);
}
}
///invio la parola///
if( send(fd_new, buf, strlen(buf)+1, 0) == SOCKET_ERROR )
error("Server: sending failure ");
strcpy(k,"no\0");
if(w==n)
strcpy(k,"ok\0");
//invio il numero di lettere azzeccate///
if( send(fd_new, k, strlen(k)+1, 0) == SOCKET_ERROR )
error("Server: sending failure ");
}
}while((tentativi!=0) || (w!=n));
//in caso di fallimento//
if(tentativi==0)
{ strcpy(buf,"hai perso la partita la parola misteriosa e");
if( send(fd_new, buf, strlen(buf)+1, 0) == SOCKET_ERROR )
error("Server: sending failure ");
}
else
{ strcpy(buf,"complimenti hai indovinato la parola!");
if( send(fd_new, buf, strlen(buf)+1, 0) == SOCKET_ERROR )
error("Server: sending failure ");
}
if (closesocket(fd_new) == SOCKET_ERROR)
error("Server: closing socket ");
if (closesocket(fd) == SOCKET_ERROR)
error("Server: closing socket ");
system("pause");
}
void client(char * server_IP)
{
SOCKET fd; // "file" descriptor for the network socket
SOCKADDR_IN saddr;
char buf[MAX_STRING];
char n[2];int tentativi;char k[3];
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 ");
////riceve dal server il mex di benvenuto//
if( recv(fd, buf, sizeof(buf), 0) == SOCKET_ERROR )
error("Client: receiving failure ");
printf("Server '%s' \n",buf);
///riceve dal server i trattini della parola misteriosa///
if( recv(fd, buf, sizeof(buf), 0) == SOCKET_ERROR )
error("Client: receiving failure ");
printf(buf);
do{ //riceve dal server l'ordine di inserire il carattere
if( recv(fd, buf, sizeof(buf), 0) == SOCKET_ERROR )
error("Client: receiving failure ");
printf(buf);
cin>>n[0];
n[1]='\0';
//invia al client la lettera
if( send(fd, n, strlen(n)+1, 0) == SOCKET_ERROR )
error("Server: sending failure ");
//riceve il messaggio dal server ,di errore nel caso non ci sia la lettera
if( recv(fd, buf, sizeof(buf), 0) == SOCKET_ERROR )
error("Client: receiving failure ");
printf(buf);
///riceve i numeri di tentativi rimasti//
if( recv(fd, n, sizeof(n), 0) == SOCKET_ERROR )
error("Client: receiving failure ");
cout<<"I tentativi rimasti sono"<<n<<endl;
//riceve dal server la parola///
if( recv(fd, buf, sizeof(buf), 0) == SOCKET_ERROR )
error("Client: receiving failure ");
printf(buf);
//riceve dal server il numero di lettere azzeccate
if( recv(fd, k, sizeof(k), 0) == SOCKET_ERROR )
error("Client: receiving failure ");
tentativi=atoi(n);
}while(n!=0 || (strcmp(k,"ok")==0));
if(tentativi==0)
{ //riceve il mex dal server che ha perso
if( recv(fd, buf, sizeof(buf), 0) == SOCKET_ERROR )
error("Client: receiving failure ");
printf(buf);
}
else
//riceve il mex che ha vinto//
{ if( recv(fd, buf, sizeof(buf), 0) == SOCKET_ERROR )
error("Client: receiving failure ");
printf(buf);
}
if (closesocket(fd) == SOCKET_ERROR)
error("Client: closing socket ");
system("pause");
}
/**********************************************
* 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
// and in wVersion the minimum of its high version and wVersionRequested.
// wVersion is the The version of the Windows Sockets specification
// that the Windows Sockets DLL expects the caller to use.
// Se WSAStartup ritorna un risultato accettabile, l'applicazione deve ancora
// verificare che il risultato sia compatibile con la sua richiesta. Ad esempio,
// con wVersionRequested=1.1 e DLL version 1.0, wVersion=1.0. Se l'applicazione
// vuole assolutamente usare la DLL 1.1, deve ancora verificare di non trovarsi
// in questo caso
// Tell the user that we couldn't find a usable winsock.dll.
if (LOBYTE(wsaData.wVersion )!=1 || HIBYTE(wsaData.wVersion)!=1) return 0;
//Everything is fine: proceed
return 1;
}
void Usage()
{
printf("\n\t Usage: tcp_sock server | client ip_server_address\n\n");
exit(1);
}
// define to save space
#define PERR(X) fprintf(stderr, X); break
void error(char* string) {
int err;
fprintf(stderr, "%s", string);
err= WSAGetLastError();
//in Windows, gli errori dovuti ai sockets sono mappati oltre 10000
switch (err)
{
case WSANOTINITIALISED:
PERR("A successful WSAStartup() must occur before using this API.");
case WSAENETDOWN:
PERR("The Windows Sockets implementation has detected that the network subsystem has failed.");
case WSAEAFNOSUPPORT:
PERR("The specified address family is not supported.");
case WSAEINPROGRESS:
PERR("A blocking Windows Sockets operation is in progress.");
case WSAEMFILE:
PERR("No more file descriptors are available.");
case WSAENOBUFS:
PERR("No buffer space is available. The socket cannot be created.");
case WSAEPROTONOSUPPORT:
PERR("The specified protocol is not supported.");
case WSAEPROTOTYPE:
PERR("The specified protocol is the wrong type for this socket.");
case WSAESOCKTNOSUPPORT:
PERR("The specified socket type is not supported in this address family.");
case WSAEADDRINUSE:
PERR("The specified address is already in use. (See setsockopt() SO_REUSEADDR option)");
case WSAEFAULT:
PERR("The namelen argument is too small (less than the size of a struct sockaddr).");
case WSAEINTR:
PERR("The (blocking) call was canceled via WSACancelBlockingCall()");
case WSAEINVAL:
PERR("The socket is already bound to an address.");
case WSAENOTSOCK:
PERR("The descriptor is not a socket.");
case WSAEADDRNOTAVAIL:
PERR("Address not availabile");
case WSAEISCONN:
PERR("The socket is already connected.");
case WSAEOPNOTSUPP:
PERR("The referenced socket is not of a type that supports the listen() operation.");
case WSAEWOULDBLOCK:
PERR("The socket is marked as non-blocking and no connections are present to be accepted.");
case WSAECONNREFUSED:
PERR("The attempt to connect was forcefully rejected.");
case WSAEDESTADDRREQ:
PERR("A destination address is required.");
case WSAENETUNREACH:
PERR("The network can't be reached from this host at this time.");
case WSAETIMEDOUT:
PERR("Attempt to connect timed out without establishing a connection");
case WSAECONNRESET:
PERR("Connection reset");
default:
fprintf(stderr, "Error reported by WSAGetLastError= %d\n Check winsock.h.\n\n", err); break;
};
exit(1);
}