#1
  1. No Profile Picture
    Junior Member
    Devshed Newbie (0 - 499 posts)

    Join Date
    Sep 2003
    Posts
    18
    Rep Power
    0

    sorry for later mistake..I hope this will be better


    Code:
    #include <winsock2.h>
    #include <stdio.h>
    #include <string.h>
    int startupServerForListening(unsigned short port);
    void shutdownServer(int socket) ;
    HANDLE threadHandle;
    
    int numConnect = 0;
    int maxConnect = 6;
    int mySocket;
    int nBytes;
    
    char strServer[100] = "Hello Clients!!";
    char *clientArrays[6];
    struct hostent *client_entry;
    char hostname[80];
    char *clientName;
    
    HANDLE mutexHandle;
    
    FD_SET masterSet;
    bool gQuitFlag = false;
    void acceptingThreadProcedure(int* serverSocket,struct sockaddr_in client ) 
    {
    	int nBytesSend;
    
    	bool firstConn = true;
    	int mySocket = *serverSocket;
    
    	SOCKET clientiparray[6];
    	for (;;) 
    	{
                       int size = sizeof(struct sockaddr);
    	unsigned int clientSocket = accept(mySocket,(struct sockaddr*)&client,&size);
    	if (clientSocket == SOCKET_ERROR) 
    	{
                          printf("Accept Failed!\n");
    	      printf("%d\n",WSAGetLastError());
    	      gQuitFlag = true;
    	      return;
    
    	} else 
    	{
    	      WaitForSingleObject(mutexHandle, INFINITE);
    	       FD_SET(clientSocket, &masterSet);
    	       client_entry = gethostbyname(clientName);
    	       if (client_entry == 0)
    	      {
    		printf("Error gethostbyname:%d\n",WSAGetLastError());
    			
    	      }
                     else
    	{
    	       numConnect++;
    	       printf("Connection NO.%d\n",numConnect);
    	      unsigned int addrLen = sizeof(client.sin_addr);
    	      printf( "Incoming Address %d IP: %s\n" ,numConnect,inet_ntoa(client.sin_addr));
    	      clientArrays[numConnect] = inet_ntoa(client.sin_addr);
    	      printf("clientArray %s\n",*(&clientArrays[numConnect]));
    
    	    ReleaseMutex(mutexHandle);
    	}
    	printf("client on %d connected\n", clientSocket);
    	if (firstConn)
    	{
    
    	      for (int i=0;i < numConnect;i++)
    	{						     nBytesSend = sizeof(strServer);			clientiparray[i] = inet_addr(clientArrays[numConnect]);	nBytesSend = send(clientiparray[i],strServer,nBytesSend,0);				
    	printf("masterset fd_set:%d\n",masterSet.fd_array[i]);
    	if (nBytesSend == SOCKET_ERROR)
    	{						WaitForSingleObject(mutexHandle, INFINITE);
    	printf("Some error from winsock :%d\n",WSAGetLastError());					ReleaseMutex(mutexHandle);
    						
    	}						printf("send message on client on %d connected\n", clientSocket);
    	}
    				
                }
    			
             }
          }
    }
    void main() 
    {
    	int serverSocket;
    	serverSocket = startupServerForListening(7654);
    	if (serverSocket == -1) 
    	{
    	printf("Network Startup Failed!\nProgram Terminating\n");
    	return;
    	}
    	mutexHandle = CreateMutex(NULL, false, NULL);
    	if (mutexHandle == NULL)
    	{
    		printf("Error creating mutex\n");
    		shutdownServer(serverSocket);
    		return;
    	}
    
    	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;
    	}
    
    	Sleep(100);
    	FD_ZERO(&masterSet);
    	for (;;) 
    	{
    	         if (gQuitFlag) 
    	        {
    		break;
    	        }						WaitForSingleObject(mutexHandle, INFINITE);
    
    	FD_SET pollingSet = masterSet;			ReleaseMutex(mutexHandle);
    	if (pollingSet.fd_count == 0) 
    	{
    		continue;
    	}
    	timeval waitTime;
    	waitTime.tv_sec = 0;
    	waitTime.tv_usec = 0;
    
    	int result = select(pollingSet.fd_count, &pollingSet, NULL, NULL, &waitTime);
    
    	if (result == 0) 
    	{
    		
    		continue;
    	}
    	if (result == SOCKET_ERROR) 
    	{
    		printf("Error in select()\n");
    		continue;
    	}
    	for (unsigned int i = 0; i < pollingSet.fd_count; i++) 
    	{
    						unsigned int clientSocket = pollingSet.fd_array[i];
    	int nBytes;					#define MAX_MESSAGE_SIZE 4096
    	char buffer[MAX_MESSAGE_SIZE];			unsigned long messageSize;				nBytes = recv(clientSocket, (char*)&messageSize, sizeof(messageSize), 0);
    	if (nBytes == SOCKET_ERROR) 
    	{
    
    							int error = WSAGetLastError();			if (error == WSAECONNRESET)
    	{
    
    							WaitForSingleObject(mutexHandle, INFINITE);		FD_CLR(clientSocket, &masterSet);			ReleaseMutex(mutexHandle);				closesocket(clientSocket);
    	printf("client on %d disconnected\n", clientSocket);	continue;
    
    	} 
             }				
    	if (nBytes == 0) 
    	{
    							WaitForSingleObject(mutexHandle, INFINITE);		FD_CLR(clientSocket, &masterSet);			ReleaseMutex(mutexHandle);				closesocket(clientSocket);
    	printf("client on %d disconnected\n", clientSocket)		continue;
    	}						messageSize = ntohl(messageSize);			nBytes = recv(clientSocket, buffer, messageSize, 0);
    	if (nBytes == SOCKET_ERROR) 
    	{
    	      printf("Recv Failed!\n");
    	      gQuitFlag = true;
    	      break;
    	}						buffer[messageSize] = '\0';
    	printf("Message Received from client on %d : %s\n", clientSocket, buffer);
    	
    	}
            }
                    shutdownServer(serverSocket);
    	printf("Press Enter to Exit ...\n");
    	getchar();	
    }
    
    int startupServerForListening(unsigned short port) 
    {
    	int error;
    	WSAData wsaData;
    	if ((error = WSAStartup(MAKEWORD(2, 2), &wsaData)) == SOCKET_ERROR)
    	{
    		printf("Could Not Start Up Winsock!\n");
    		return -1;
    	}
    	// create my socket
    	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;
    	}
    	//get my socket name
    	if (getsockname(mySocket,(struct sockaddr*)&server,(int*)sizeof(server))==0)
    	{
    		perror("getsockname:");
    		printf("getsockname Fail!!!\n");
    	}
    	if (gethostname(hostname,sizeof(hostname)))
    	{
    		printf("Error gethostname:%d\n",WSAGetLastError());
    	}else
    	{
    		printf("Host name: %s\n",hostname);
    			
    	}
    	
    	// mark my socket for listening
    	if (listen(mySocket, maxConnect) == SOCKET_ERROR)
    	{
    		printf("Listen Failed!\n");
    		closesocket(mySocket);
    		return -1;
    	}
    
    	printf("Server Started\n");
    
    	return mySocket;
    }
    //function to shut down socket and 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");
    }
  2. #2
  3. No Profile Picture
    Junior Member
    Devshed Newbie (0 - 499 posts)

    Join Date
    Sep 2003
    Posts
    18
    Rep Power
    0
    This is source code for multithread-server .It should broadcast messages to clients but when I execute program it can not send anything out to client and I got winsock error 10038 "Socke t operation on non-socket" ...
    any suggestion????
    Thank you.
  4. #3
  5. not a fan of fascism (n00b)
    Devshed Frequenter (2500 - 2999 posts)

    Join Date
    Feb 2003
    Location
    ct
    Posts
    2,756
    Rep Power
    95
    you have forgetten to tell us where the error occurs, but in any event...
    Code:
    void acceptingThreadProcedure(int* serverSocket,struct sockaddr_in client )
    -now i havent programmed in win32 in over 5 months. but if my memory serves me correctly a thread is only passed one parameter. it is up to you to put all the necessary arguments for the thread into a structure and then pass the struct by reference to the thread. now in the event i have lost my mind and am wrong about that, there still is the issue that this thread function is declared as having 2 parameters, but how is it recieving the 2nd one? you only pass the socket handle, where is the address structure?
  6. #4
  7. No Profile Picture
    Junior Member
    Devshed Newbie (0 - 499 posts)

    Join Date
    Sep 2003
    Posts
    18
    Rep Power
    0
    thank you very much for your suggestion infamous41md .
    my error is when server try to send message to all clients winsock error10038:Operation Socket on non-socket
    I think I should learn more about FD_SET and CreateThread ,however, great thanks if I can figure out I will tell.
  8. #5
  9. not a fan of fascism (n00b)
    Devshed Frequenter (2500 - 2999 posts)

    Join Date
    Feb 2003
    Location
    ct
    Posts
    2,756
    Rep Power
    95
    clientiparray[i] = inet_addr(clientArrays[numConnect]); nBytesSend = send(clientiparray[i],strServer,nBytesSend,0);

    that is the problem. your trying to send on a socket that you have assigned to be network byte ordered address.

IMN logo majestic logo threadwatch logo seochat tools logo