winsock multithreaded server

This is a discussion on winsock multithreaded server within the Networking/Device Communication forums, part of the General Programming Boards category; Hii!! this is urgent , any help would be greatly appreciated!! i have a multithreaded server and many clients connect ...

  1. #1
    Registered User
    Join Date
    Oct 2009
    Posts
    4

    winsock multithreaded server

    Hii!!
    this is urgent , any help would be greatly appreciated!!
    i have a multithreaded server and many clients connect to it .The server client intercat in a derilaized manner i.e clienr sends something and based on what client sends the server responds appropraitely..So the thing is i have 2 clients and both do the same intercation with the server.While the first client works fine ,the second one fails to recv data and send data at diiferent points in different runs..Dont know what is the problem... plz help!!!

  2. #2
    pwning noobs Zlatko's Avatar
    Join Date
    Jun 2009
    Location
    The Great White North
    Posts
    132
    Hello Hardy.
    You should post the server and client code so that people can have a look. If you can post a minimal version of client and server that exhibit the same problem, that would be even better. If it always works properly with one client, you likely have an issue with interacting threads. Make sure all data shared by threads is protected from simultaneous access.

  3. #3
    Registered User
    Join Date
    Oct 2009
    Posts
    4
    The client and server were coded using the sample code in the msdn website [I don't have the code right now, I'll post it on a later date if required].
    The 2 clients which are trying to connect are from the same machine. Does it affect the interaction of each pair? Different runs are giving me different results each time. And I don't get what exactly you meant my "interacting threads".
    PLz Help!
    THank you

  4. #4
    pwning noobs Zlatko's Avatar
    Join Date
    Jun 2009
    Location
    The Great White North
    Posts
    132
    Having both clients on the same machine does not matter.

    If your server does not take long to process a client request, then consider servicing multiple clients with the select function, instead of multiple threads. The programming will be less complicated.

    By "interacting threads", I mean that both threads are accessing, for read and write, the same data at the same time. When data is shared, you need to ensure that only one thread uses it at a time. You do that by setting up a Mutex or CriticalSection object. See MSDN for details.

    I cannot say anything specific without seeing the code.

    Best regards.

  5. #5
    Registered User
    Join Date
    Oct 2009
    Posts
    4
    i read somewhere that every connection is given a separate socket and a socket is identified by the tuple of destination adress,destination port,source address source port.So in case of the same client connecting to the same server twice simultaneosly could the problem be that the socket is same?
    if so how can i know what port number my client is using and how can i make sure the client port number is different!!!!

  6. #6
    pwning noobs Zlatko's Avatar
    Join Date
    Jun 2009
    Location
    The Great White North
    Posts
    132
    Quote Originally Posted by hardy1989 View Post
    if so how can i know what port number my client is using and how can i make sure the client port number is different!!!!

    You don't need to worry about that. The OS will take care of it and I'm not sure how to get the port number assigned by the OS to the client.

    Every connection from client to server results in a new socket on the server. The accept function on the server returns a new socket.

    Every connection form a client, even many connections from a single client, is on its own socket. For each connection, the client calls socket, then it calls connect on that socket.

    Every client connects to the same port on the server, but the OS then assigns a unique port on the server (and on the client) for the connection. You don't need to worry about what the port number is.

  7. #7
    Registered User
    Join Date
    Oct 2009
    Posts
    4
    Here is the code used in the server. Some of the data sent by the server is lost. And there is no regular pattern, results differ even with same test runs.
    Server Code:
    Code:
    int __cdecl main(void) 
    {
    	// Creating MySQL Connection
    	char query[180];
    	mysql_init(&mysql);
    	if(mysql_real_connect(&mysql, "localhost", "root", "security", "demo",3306, NULL, 0))
    		cout<<"Connected to the database."<<endl;
    	else {
    		cout<<"Connection to the database failed."<<endl;
    		exit(0);
    }
    
       //Creating Socket
       
       WSADATA wsaData;
       SOCKET ListenSocket = INVALID_SOCKET;
       SOCKET ClientSocket = INVALID_SOCKET;
       struct addrinfo *result = NULL,
                        hints;
       char recvbuf[DEFAULT_BUFLEN];
       int iResult, iSendResult;
       int recvbuflen = DEFAULT_BUFLEN;
       int clientid=0;
       Clientinfo temp_client[10];
    
    	// for our thread
    	DWORD thread; 
        
        // Initialize Winsock
        iResult = WSAStartup(MAKEWORD(2,2), &wsaData);
        if (iResult != 0) {
            printf("WSAStartup failed: %d\n", iResult);
            return 1;
        }
    
        ZeroMemory(&hints, sizeof(hints));
        hints.ai_family = AF_INET;
        hints.ai_socktype = SOCK_STREAM;
        hints.ai_protocol = IPPROTO_TCP;
        hints.ai_flags = AI_PASSIVE;
    
        // Resolve the server address and port
        iResult = getaddrinfo(NULL, DEFAULT_PORT, &hints, &result);
        if ( iResult != 0 ) {
            printf("getaddrinfo failed: %d\n", iResult);
            WSACleanup();
            return 1;
        }
    
        // Create a SOCKET for connecting to server
        ListenSocket = socket(result->ai_family, result->ai_socktype, result->ai_protocol);
        if (ListenSocket == INVALID_SOCKET) {
            printf("socket failed: %ld\n", WSAGetLastError());
            freeaddrinfo(result);
            WSACleanup();
            return 1;
        }
    printf("created socket\n");
        // Setup the TCP listening socket
        iResult = bind( ListenSocket, result->ai_addr, (int)result->ai_addrlen);
        if (iResult == SOCKET_ERROR) {
            printf("bind failed: %d\n", WSAGetLastError());
            freeaddrinfo(result);
            closesocket(ListenSocket);
            WSACleanup();
            return 1;
    	}
    	printf("bind complete\n");
        freeaddrinfo(result);
    
        iResult = listen(ListenSocket, SOMAXCONN);
        if (iResult == SOCKET_ERROR) {
            printf("listen failed: %d\n", WSAGetLastError());
            closesocket(ListenSocket);
            WSACleanup();
            return 1;
        }
    	//Thread for checking
    	CreateThread(NULL, 0, check, NULL, 0, &thread);
        
    	//Thread for database
    	//CreateThread(NULL, 0, populate_database, NULL, 0, &thread);
        //MYSQL mysql;
    MYSQL_RES *res;
    MYSQL_ROW row;
    //For the last mesg sequence number
    			sprintf(query,"CREATE TABLE SEQ(srno INT, last_id INT)");
    			mysql_real_query(&mysql,query,(unsigned int)strlen(query));
    			res = mysql_use_result(&mysql);
    			mysql_free_result(res);
    
    	// Accept a client socket
    	printf("waiting fr client\n");
    	
    	while(true){
    		cout<<"waiting......"<<endl;
    		try{
    			cout<<"!!!!!!!!!!! \t"<<clientid<<"\t !!!!!!!!!!!!!!!!"<<endl;
    		//	print_values();
    			cout<<"!!!!!!!!!!! \t"<<clientid<<"\t !!!!!!!!!!!!!!!!"<<endl;
    			ClientSocket = accept(ListenSocket, NULL, NULL);
    			cout<<"found"<<endl;
    			if (ClientSocket == INVALID_SOCKET) {
    				printf("accept failed: %d\n", WSAGetLastError());
    				closesocket(ListenSocket);
    				WSACleanup();
    				return 1;
    			}
    			cout<<"accepted client"<<endl;
    			clientid++;
    			sprintf(query,"CREATE TABLE STORAGE_%d(srno INT, id INT, mesg VARCHAR(10000))",clientid);
    			mysql_real_query(&mysql,query,(unsigned int)strlen(query));
    			res = mysql_use_result(&mysql);
    			mysql_free_result(res);
    			
    			//Clientinfo temp_client;
    			temp_client[clientid].Clientid = clientid;
    			temp_client[clientid].ClientSocket = ClientSocket;
    			//temp_client.pointer_cache = &cache;
    			CreateThread(NULL, 0,receive_cmds,(LPVOID)&(temp_client[clientid]), 0, &thread); 
    			cout<<"Majak majak mein "<<ClientSocket<<endl;
    			 //closesocket(ClientSocket);
    			//free(temp_client);
    		}
    		catch(exception e){
    			cout<<"Caught in Main\t"<<e.what()<<endl;
    		}
    	}
    
    
        // No longer need server socket
        closesocket(ListenSocket);
    
        // cleanup
        closesocket(ClientSocket);
        WSACleanup();
    
        //print_values();
    	return 0;
    }

  8. #8
    pwning noobs Zlatko's Avatar
    Join Date
    Jun 2009
    Location
    The Great White North
    Posts
    132
    Hardy, I'll look at it in the next few days. Post the client too. Generally you want to make it as easy as possible for people that are helping you.

    Edit.

    I cannot tell from looking at the code what the problem is. I don't know what your thread worker function looks like because it's not posted.

    I suggest you make sure that you are linking in windows multithreaded libraries and mysql multithreaded libraries, if there exists such a thing.

    Make sure your clientid index does not go past the temp_client array.

    Try a simple client/server without mysql, and see if you can get correct results. Then add the database access.

    Good luck.
    Last edited by Zlatko; 11-04-2009 at 06:07 AM.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. FTP and Ident Server :: Winsock
    By kuphryn in forum Networking/Device Communication
    Replies: 2
    Last Post: 03-13-2004, 08:16 PM
  2. Multithreaded Winsock
    By X PaYnE X in forum Windows Programming
    Replies: 6
    Last Post: 01-05-2004, 09:00 AM
  3. Simple? winsock client - server problem
    By knutso in forum Windows Programming
    Replies: 2
    Last Post: 03-26-2003, 04:51 AM
  4. FTP Server :: Winsock
    By kuphryn in forum Windows Programming
    Replies: 2
    Last Post: 10-03-2002, 08:14 PM
  5. socket question
    By Unregistered in forum C Programming
    Replies: 3
    Last Post: 07-19-2002, 02:54 PM

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21