Thread: my server program auto shut down

  1. #1
    Registered User
    Join Date
    Mar 2004
    Posts
    114

    my server program auto shut down

    Code:
    #include <windows.h>
    #pragma comment(lib, "wsock32.lib")
    
    #include <winsock.h>
    #include <stdio.h>
    
    
    
    
    
    
    #define NETWORK_ERROR -1
    #define NETWORK_OK     0
    
    void ReportError(int, const char *);
    
    
    int WINAPI WinMain(HINSTANCE hInst, HINSTANCE hPrevInst, LPSTR lpCmd, int nShow) {
    	WORD sockVersion;
    	WSADATA wsaData;
    	int nret;
    	SOCKET listeningSocket;
    	SOCKADDR_IN serverInfo;
    	SOCKET theClient;
    
    	sockVersion = MAKEWORD(1, 1);			// We'd like Winsock version 1.1
    
    
    
    	// We begin by initializing Winsock
    	WSAStartup(sockVersion, &wsaData);
    
    
    	// Next, create the listening socket
    
    
    	listeningSocket = socket(AF_INET,		// Go over TCP/IP
    			         SOCK_STREAM,   	// This is a stream-oriented socket
    				 IPPROTO_TCP);		// Use TCP rather than UDP
    
    	if (listeningSocket == INVALID_SOCKET) {
    		nret = WSAGetLastError();		// Get a more detailed error
    		ReportError(nret, "socket()");		// Report the error with our custom function
    
    		WSACleanup();				// Shutdown Winsock
    		return NETWORK_ERROR;			// Return an error value
    	}
    
    
    	// Use a SOCKADDR_IN struct to fill in address information
    
    
    	serverInfo.sin_family = AF_INET;
    	serverInfo.sin_addr.s_addr = INADDR_ANY;	// Since this socket is listening for connections,
    							// any local address will do
    	serverInfo.sin_port = htons(8888);		// Convert integer 8888 to network-byte order
    							// and insert into the port field
    
    
    	// Bind the socket to our local server address
    	nret = bind(listeningSocket, (LPSOCKADDR)&serverInfo, sizeof(struct sockaddr));
    
    	if (nret == SOCKET_ERROR) {
    		nret = WSAGetLastError();
    		ReportError(nret, "bind()");
    
    		WSACleanup();
    		return NETWORK_ERROR;
    	}
    
    
    	// Make the socket listen
    	nret = listen(listeningSocket, 10);		// Up to 10 connections may wait at any
    							// one time to be accept()'ed
    
    	if (nret == SOCKET_ERROR) {
    		nret = WSAGetLastError();
    		ReportError(nret, "listen()");
    
    		WSACleanup();
    		return NETWORK_ERROR;
    	}
    
    
    	// Wait for a client
    
    
    
    
    	while(1)
    	{
    
    	theClient = accept(listeningSocket,
    			   NULL,			// Address of a sockaddr structure (see explanation below)
    			   NULL);			// Address of a variable containing size of sockaddr struct
    				MessageBox(hInst, "CONNECTED", "This program is:", MB_OK | MB_ICONINFORMATION);
    
    	if (theClient == INVALID_SOCKET) {
    		nret = WSAGetLastError();
    		ReportError(nret, "accept()");
    		WSACleanup();
    		return NETWORK_ERROR;
    	}
    	else
    	{
    
    		char buffer[256];		// On the stack
    //		char *buffer = new char[256];	// or on the heap
    				MessageBox(hInst, "CONNECTED", "This program is:", MB_OK | MB_ICONINFORMATION);
    		nret = recv(theClient,
    	    buffer,
    	    256,	// Complete size of buffer
    	    0);
    	
    		if (nret == SOCKET_ERROR) {// Get a specific code// Handle accordingly
       return NETWORK_ERROR;	} 
    
    		else if (buffer == "check_network")
    		{
    			MessageBox(hInst, "checkNW", "This program is:", MB_OK | MB_ICONINFORMATION);
    		;}
    		else if (buffer == "shutdown")
    		{
    			MessageBox(hInst, "shutdown", "This program is:", MB_OK | MB_ICONINFORMATION);
    		;}
    		else if (buffer == "restart")
    		{
    			MessageBox(hInst, "restartt", "This program is:", MB_OK | MB_ICONINFORMATION);
    		;}
    		else if (buffer == "lower_volume")
    		{
    			MessageBox(hInst, "lowervol", "This program is:", MB_OK | MB_ICONINFORMATION);
    		;}
    //	listeningSocket = theClient;
    	}
    		;
    	}
    
    
    
    //delete [] buffer;		// Manipulate buffer, then delete if and only if
    				// buffer was allocated on heap
    
    
    
    
    
       // nret contains the number of bytes received
    	
    	
    //	listeningSocket = theClient;
    
    	// Send and receive from the client, and finally,
    	closesocket(theClient);
    	closesocket(listeningSocket);
    
    
    	// Shutdown Winsock
    	WSACleanup();
    	return NETWORK_OK;
    }
    
    
    
    
    
    void ReportError(int errorCode, const char *whichFunc) {
       char errorMsg[92];					// Declare a buffer to hold
    							// the generated error message
       
       ZeroMemory(errorMsg, 92);				// Automatically NULL-terminate the string
    
       // The following line copies the phrase, whichFunc string, and integer errorCode into the buffer
       sprintf(errorMsg, "Call to %s returned error %d!", (char *)whichFunc, errorCode);
    
       MessageBox(NULL, errorMsg, "socketIndication", MB_OK);
    }

    here's a prototype of my code
    basically it's a server allowing a custom client(that i am going to create soon) to connect to it.
    the problem is that when a client connects, and if the client shuts down instead of properly closing socket and disconnecting, the whole server program shuts down

    is there anyway to prevent the server program from shutting down? I suspect it's due to the error checking codes but i cant put my finger on it

    copied most of the codes from
    johnie's winsock tutorial btw

  2. #2
    Carnivore ('-'v) Hunter2's Avatar
    Join Date
    May 2002
    Posts
    2,879
    Ok, first things first: On every error checking thing AFTER you've successfully created listeningSocket, you need to closesocket() on listeningSocket if there's an error. For example:
    Code:
    if (nret == SOCKET_ERROR) {
    	nret = WSAGetLastError();
    	ReportError(nret, "bind()");
    	closesocket(listeningSocket);
    	WSACleanup();
    	return NETWORK_ERROR;
    }
    And here:
    Code:
    if (nret == SOCKET_ERROR) {// Get a specific code// Handle accordingly
       return NETWORK_ERROR;	}
    This is your problem line. If you return, you quit. In your case, you quit without freeing any of the resources you allocated, meaning you have a memory leak. Instead of returning, you should just do nothing and let it go back to the beginning of the loop.... except for one thing, which I will explain later.

    Here:
    Code:
    else if (buffer == "check_network")
    A few problems with this. First, you can't compare strings like that... you need to use strcmp() (it will return 0 for the same, non-zero if they're different). Second, unless your client sent a NULL zero at the end of the string, your string will be 256 characters long (Actually, probably a lot longer because chances are there won't be too many 0's in the random system memory) and you'll get a crash. Also, you're not taking into account that you might not get the whole message in one recv().

    Code:
    {
    	MessageBox(hInst, "shutdown", "This program is:", MB_OK | MB_ICONINFORMATION);
    ;}
    
    (...)
    
    	}
    		;
    	}
    Why do you have those semicolons? Those are 'blank' lines, they don't do anything except clutter your code, make it unreadable, whatever.

    Code:
    //	listeningSocket = theClient;
    I'm glad that's commented out. But why is that even there, commented or not??

    Code:
    // Send and receive from the client, and finally,
    	closesocket(theClient);
    This line should not be HERE. Each time you call accept(), you're creating a new socket, and not closing it. At the end of the program, you're closing only one socket - the last socket that you created with accept(). Instead, this line should go here:
    Code:
    		{
    			MessageBox(hInst, "lowervol", "This program is:", MB_OK | MB_ICONINFORMATION);
    		;}
    
    	}
    	closesocket(theClient);
    		;  //Again, why is THIS here??
    }
    That about sums up the problems with your code (I can't think of anything else at the moment), other than the poor indentation. If you need more help, feel free to post more questions.

    Just as a side note though, I hope I don't offend you or anything, but judging from your code I think you should probably get some more experience with the basics of C(++) before starting to learn Windows/Networking. If you're really determined to learn this stuff right now though, I wish you good luck and quick learning!
    Just Google It. √

    (\ /)
    ( . .)
    c(")(") This is bunny. Copy and paste bunny into your signature to help him gain world domination.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Program Plan
    By Programmer_P in forum C++ Programming
    Replies: 0
    Last Post: 05-11-2009, 01:42 AM
  2. telnet server, how to program a backspace
    By Mastermosley in forum C# Programming
    Replies: 5
    Last Post: 03-22-2009, 02:14 AM
  3. Client-server system with input from separate program
    By robot-ic in forum Networking/Device Communication
    Replies: 3
    Last Post: 01-16-2009, 03:30 PM
  4. Function in a Server program
    By nick048 in forum C Programming
    Replies: 1
    Last Post: 03-31-2007, 01:41 AM
  5. having a program shut down windows
    By boy1015 in forum C++ Programming
    Replies: 5
    Last Post: 02-05-2002, 07:32 PM