Gå til innhold

Winsock får ikke sendt fra server til client.


Anbefalte innlegg

har et proplem får ikke sendt en melding fra serveren til client. så det er bare serveren som ser hva som skjer.

her er koden

int startupClient(unsigned short port, const char* serverName);

// -----------------------------------------------------------------------------------
// shutdownClient() - will close the socket specified and clean up winsock.
void shutdownClient(int clientSocket);

// winsock for our network communication
#include <winsock2.h>
// stdio for I/O
#include <stdio.h>

HANDLE threadHandle;
HANDLE mutexHandle;

int main() {
printf("-Welcome to Networking com !\n");
printf("-created by fredrik\n-special thanks to www.gametutorials.com \n\n- this is theClientSide\n\n");

// my socket
int mySocket;

// create our client
mySocket = startupClient(7654, "localhost");


if (mySocket == -1) {
 // hmm an error occurred
 // shutdown our client and bail
 printf("an error has ocurred in mysocket, closing porgram now");
 shutdownClient(mySocket);
 return 0;
}  

mutexHandle = CreateMutex(NULL, false, NULL);

// number of bytes sent
int nBytes;
int Bytes;

// I will define a message size so we will know how much data we will send and receive
#define MAX_MESSAGE_SIZE 4096
char buffer[MAX_MESSAGE_SIZE];
char Message[MAX_MESSAGE_SIZE];

printf("Input text to send and press Enter\nType 'quit' to exit\n");

// the main loop
for (;;) {
 // get some input from the command line
 gets(buffer);

 // check if quit was typed, then exit
 if (strcmp(buffer, "quit") == 0) {
 	break;
 }

 // get our message size
 unsigned long messageSize = strlen(buffer);

 // fix our byte ordering
 messageSize = htonl(messageSize);

 // send the message size
 if ((nBytes = send(mySocket, (char*)&messageSize, sizeof(messageSize), 0)) == SOCKET_ERROR) {
 	printf("Send Failed!\n");
 }

 // re-fix our byte ordering
 messageSize = ntohl(messageSize);

 // send the actual message
 if ((nBytes = send(mySocket, buffer, messageSize, 0)) == SOCKET_ERROR) {
 	printf("Send Failed!\n");
       }  	
 //recive the message	
 Bytes = recv(mySocket, Message, sizeof(Message), 0);
 
       if ((nBytes = recv(mySocket, buffer, messageSize, 0)) == SOCKET_ERROR) {
           printf("recive failed.\n");	
 }
}

// shutdown our client
shutdownClient(mySocket);
}

int startupClient(unsigned short port, const char* serverName) {
// an error code we will use to get more information about our errors
int error;

// the winsock data structure
WSAData wsaData;

// startup winsock
if ((error = WSAStartup(MAKEWORD(2, 2), &wsaData)) == SOCKET_ERROR) {
 printf("Could Not Start Up Winsock!\n");
 return -1;
}

// create my socket
int mySocket = socket(AF_INET, SOCK_STREAM, 0);

// make sure nothing bad happened
if (mySocket == SOCKET_ERROR) {
 printf("Error Opening Socket!\n");
 return -1;
}

struct hostent *host_entry;

// setup the host entry
if ((host_entry = gethostbyname(serverName)) == NULL) {
 printf("Could not find host!\n");
}

struct sockaddr_in server;

// fill in the server socket info
server.sin_family = AF_INET;
server.sin_port = htons(port);
server.sin_addr.s_addr = *(unsigned long*) host_entry->h_addr;

// connect to the server
if (connect(mySocket, (sockaddr*)&server, sizeof(server)) == SOCKET_ERROR) {
 printf("Error connecting to server!\n");
}

printf("Client Started\n");

return mySocket;
}

void shutdownClient(int clientSocket) {
// close our socket
closesocket(clientSocket);

// shut down winsock
WSACleanup();

printf("Client Shutdown\n");
}

dette var client. nå kommer server.


#include <winsock2.h>
// stdio for I/O
#include <stdio.h>


int startupServerForListening(unsigned short port);


void shutdownServer(int socket);

HANDLE threadHandle;

HANDLE mutexHandle;

FD_SET masterSet;

bool gQuitFlag = false;


void acceptingThreadProcedure(int* serverSocket) {

// copy my socket over to a local variable
int mySocket = *serverSocket;

// run forever
for (;;) {

 // accept a client like normal
 unsigned int clientSocket = accept(mySocket, 0, 0);

 // make sure things are ok
 if (clientSocket == SOCKET_ERROR) {

 	// just stop of we received any errors
 	printf("Accept Failed!\n");

 	// signal to quit the application
 	gQuitFlag = true;

 	// and quit this thread
 	return;

 } else {


 	// lock the mutex
 	WaitForSingleObject(mutexHandle, INFINITE);

 	FD_SET(clientSocket, &masterSet);

 	ReleaseMutex(mutexHandle);

 	// a quick message
 	printf("client on %d connected\n", clientSocket);
 }
}
}


int main() {
printf("Welcome to Networking com !\ncreated by Fredrik \nspecial thanks to");
printf(" www.gametutorials.com \n\n\nthis is the serverSide\n\n");

// Startup our network as usual.

// the socket my server will use for listening
int serverSocket;

int nBytes;

int Bytes;

// startup my network utilities with my handy functions
serverSocket =startupServerForListening(7654);

// check for errors
if (serverSocket == -1) {
 printf("Network Startup Failed!\nProgram Terminating\n");
 return 0;
}



// create the mutex
mutexHandle = CreateMutex(NULL, false, NULL);
if (mutexHandle == NULL) {
 printf("Error creating mutex\n");
 shutdownServer(serverSocket);
 return 0;
}

// create the thread
int threadId;
threadHandle = CreateThread(NULL, 0, (LPTHREAD_START_ROUTINE)acceptingThreadProcedure, &serverSocket, 0, (LPDWORD)&threadId);
if (threadHandle == NULL) {
 printf("Could not start acceptance thread\n");
 shutdownServer(serverSocket);
 return 0;
}

// sleep the main() so the acceptance thread has time to start ... this is cheesy
Sleep(100);

// Now that that is all over with, it's down to business.

// It's always a good idea to initialize our structures before we access them, so let's zero our masterSet.
FD_ZERO(&masterSet);

// the main loop ... run forever
for (;;) {
 if (gQuitFlag) {
 	break;
 }
 // lock the mutex
 WaitForSingleObject(mutexHandle, INFINITE);

 Remember,

 FD_SET pollingSet = masterSet;

 // unlock the mutex
 ReleaseMutex(mutexHandle);

 // check if our set is empty
 if (pollingSet.fd_count == 0) {
 	continue;
 }

 // the wait time
 timeval waitTime;
 waitTime.tv_sec = 0;
 waitTime.tv_usec = 0;

 
 int result = select(pollingSet.fd_count, &pollingSet, NULL, NULL, &waitTime);

 if (result == 0) {
 	// no sockets have data
 	continue;
 }

 // check for errors
 if (result == SOCKET_ERROR) {
 	printf("Error in select()\n");
 	continue;
 }

 // Now that we have the polling set that contains just the sockets that have data, let's step through
 // the list of sockets and read from them all.

 // for every socket in my polling set
 for (unsigned int i = 0; i < pollingSet.fd_count; i++) {

 	// We can access the socket list directly using the fd_array member of the FD_SET
 	unsigned int clientSocket = pollingSet.fd_array[i];

 	// a buffer to hold my data
 	#define MAX_MESSAGE_SIZE 4096
 	char buffer[MAX_MESSAGE_SIZE];

 	// the size of the message that is being sent
 	unsigned long messageSize;

 	// receive the message size first
 	nBytes = recv(clientSocket, (char*)&messageSize, sizeof(messageSize), 0);

 	// check for errors
 	if (nBytes == SOCKET_ERROR) {

   // Uh Oh!  We have our first real use of error handling!  Something can happen here that is
   // pretty significant.  Let's grab the error number from winsock.
   int error = WSAGetLastError();


   // handle the dropped connection
   if (error == WSAECONNRESET) {

   	// When we receive this error.  Just get a lock on the master set, and remove this socket from
   	// set using the FD_CLR() macro.

   	// lock our mutex
   	WaitForSingleObject(mutexHandle, INFINITE);

   	// remove the socket from our master set
   	FD_CLR(clientSocket, &masterSet);

   	// unlock our mutex
   	ReleaseMutex(mutexHandle);

   	// close the socket on our side, so our computer cleans up properly
   	closesocket(clientSocket);

   	// a quick message
   	printf("client on %d disconnected\n", clientSocket);

   	// move on to the next client
   	continue;

   } else {

   	// we failed, but it wasn't an error we were expecting ... so kill the server
   	printf("Recv Failed!\n");
   	gQuitFlag = true;
   	break;

   }
 	}


 	if (nBytes == 0) {
   // lock our mutex
   WaitForSingleObject(mutexHandle, INFINITE);

   // remove the socket from our master set
   FD_CLR(clientSocket, &masterSet);

   // unlock our mutex
   ReleaseMutex(mutexHandle);

   // close the socket on our side, so our computer cleans up properly
   closesocket(clientSocket);

   // a quick message
   printf("client on %d disconnected\n", clientSocket);

   // move on to the next client
   continue;
 	}

 	messageSize = ntohl(messageSize);

 	// receive the reset of the message
 	nBytes = recv(clientSocket, buffer, messageSize, 0);
 	
 	Bytes = send(clientSocket, (char*)&messageSize, sizeof(messageSize), 0);

 	// check for error
 	if (nBytes == SOCKET_ERROR) {
   printf("Recv Failed!\n");
   gQuitFlag = true;
   break;
 	}

 	// remember this is a string, so terminate the buffer so we can print it
 	buffer[messageSize] = '\0';

 	// print the message
 	printf("Message Received from client on %d : %s\n", clientSocket, buffer);
 }
}

// cleanup
shutdownServer(serverSocket);

printf("Press Enter to Exit ...\n");
getchar();

}

// -----------------------------------------------------------------------------------
// startupServerForListening() - a function to startup winsock, and open a socket for listening

int startupServerForListening(unsigned short port) {
// an error code we will use to get more information about our errors
int error;

// the winsock data structure
WSAData wsaData;

// startup winsock
if ((error = WSAStartup(MAKEWORD(2, 2), &wsaData)) == SOCKET_ERROR) {
 printf("Could Not Start Up Winsock!\n");
 return -1;
}

// create my socket
int mySocket = socket(AF_INET, SOCK_STREAM, 0);

// make sure nothing bad happened
if (mySocket == SOCKET_ERROR) {
 printf("Error Opening Socket!\n");
 return -1;
}

// the address structure
struct sockaddr_in server;

// fill the address structure with appropriate data
server.sin_family = AF_INET;
server.sin_port = htons(port);
server.sin_addr.s_addr = INADDR_ANY;

// and now bind my socket
if (bind(mySocket, (sockaddr*)&server, sizeof(server)) == SOCKET_ERROR) {
 printf("Bind Failed!\n");
 closesocket(mySocket);
 return -1;
}

// mark my socket for listening
if (listen(mySocket, 5) == SOCKET_ERROR) {
 printf("Listen Failed!\n");
 closesocket(mySocket);
 return -1;
}

printf("Server Started\n");

return mySocket;
}

// -----------------------------------------------------------------------------------
// shutdownServer() - a function to shutdown a socket and clean up winsock

void shutdownServer(int socket) {

// kill my thread and my handle
WaitForSingleObject(threadHandle, INFINITE);
CloseHandle(threadHandle);
CloseHandle(mutexHandle);

// close our socket
closesocket(socket);

// shut down winsock
WSACleanup();

printf("Server Shutdown\n");
}

 

edit:vet at det er litt klip fra andre sin kode. eller lettere sakt fra den tutorialen jeg brukte.

 

edit 2: fant feilen det var så enkelt som at jeg ikke skreiv ut stringen.

Endret av Fredrik90
Lenke til kommentar

Opprett en konto eller logg inn for å kommentere

Du må være et medlem for å kunne skrive en kommentar

Opprett konto

Det er enkelt å melde seg inn for å starte en ny konto!

Start en konto

Logg inn

Har du allerede en konto? Logg inn her.

Logg inn nå
  • Hvem er aktive   0 medlemmer

    • Ingen innloggede medlemmer aktive
×
×
  • Opprett ny...