none
WinSock Help RRS feed

  • Question

  • So I have a client,a server,and a file that stores the ip of all servers.When the server launches it writes to that file it's ip address.

    The file is on a webhost.

    When the client gets launched,it connects to the file,reads the ip addresses,and lists them,the user choses one and then connects.

    The server does connect to the file and it does post it's ip address.The client does connect to the file and it reads the ip addresses,but when it tries to connect,nothing happens.

    This is the script that is accessed:

    <?php
    
    // The only thing really missing is authentication.
    // For example, it could check $Data for an encrypted, or cryptographic string, etc.
    
    
    
    $Data = explode('|', $_POST['D']);				// Data sent from HTTP request seperated into an array
    
    $IPFileName = "IPList";													// May need cleared once in a while (when a Server doesn't successfully shut down)
    
    
    
    // ---- Constants -------------------
    $AddServer		= '0';														// If $Data[0] == $AddServer, add a server to the list, etc.
    $RemServer		= '1';
    $GetServers		= '2';
    
    
    
    
    if ($Data[0] == $AddServer) {									// Add an IP to the list...
    
    	$IPFile = fopen($IPFileName, 'r');
    	$IPSize = filesize($IPFileName);
    	$IPList = fread($IPFile, $IPSize);
    	fclose($IPFile);
    
    	$IPList .= $Data[1].'|';												// Add the IP to the list...
    
    	$IPFile = fopen($IPFileName, 'w');							// Update the file...
    	fwrite($IPFile, $IPList);
    	fclose($IPFile);
    
    	exit();
    
    }
    
    if ($Data[0] == $RemServer) {									// Remove an IP from the list...
    
    	$IPFile = fopen($IPFileName, 'r');
    	$IPSize = filesize($IPFileName);
    	$IPList = fread($IPFile, $IPSize);
    	fclose($IPFile);
    
    	$RemMe = $Data[1].'|';
    	$IPList = str_replace($RemMe, "", $IPList);			// Remove the IP from the list...
    
    	$IPFile = fopen($IPFileName, 'w');							// Update the file...
    	fwrite($IPFile, $IPList);
    	fclose($IPFile);
    
    	exit();
    
    }
    
    if ($Data[0] == $GetServers) {									// Get the IPs from the list...
    
    	$IPFile = fopen($IPFileName, 'r');
    	$IPSize = filesize($IPFileName);
    	$IPList = fread($IPFile, $IPSize);
    	fclose($IPFile);
    
    	echo $IPList;																	// Return the list of IPs (of all active Servers) deliminated by '|'
    
    	exit();
    
    }
    
    
    
    
    ?>

    Client code:

    // ---------------------------------
    // ---- Type defines ----------------
    
    typedef unsigned long	U32;
    typedef unsigned short	U16;
    typedef unsigned short	U8;
    
    typedef signed long		S32;
    typedef signed short	S16;
    typedef signed short	S8;
    
    
    
    // -----------------------------------
    // ------ Defines ---------------------
    
    #define WEBSITE			"masterserver.x10host.com"				// Full website URL, withouth HTTP (raises exe size)
    #define WEBPAGE			"/Server.php"					// The page of the Server Script (proceed with '\')
    #define IPFILE			"/IPList"
    
    #define REQUEST			"GET " IPFILE " HTTP/1.1\r\nHost: " WEBSITE "\r\n\r\n"
    
    #define WINTITLE		"Client Program"
    #define WINCLASS		"CNTCLASS"
    
    #define WINWIDTH		384
    #define WINHEIGHT		512
    
    #define PORT			7171							// MUST be the same for the server, and PF'ed!
    #define MAXSERVERS		16								// Max possible servers
    
    #define EDITID			200								// The edit control ID
    #define LISTID			201								// The listbox control ID
    
    #define CW_DEFAULT		0
    
    
    // -----------------------------------
    // ------ Server Messages -------------
    
    #define cAddIP			0			// Send this to add an IP to the list
    #define cRemIP			1			// Send this to remove an IP from the list
    #define cGetIPs			2			// Send this to get a list of all Server IPs
    
    
    
    // ------------------------------------
    // ----- Global Variables --------------
    
    HWND hWnd;
    SOCKET ServSock;
    
    char* ServerIPList;
    char ServerIP[17];
    
    
    
    // ----------------------------~~~~~~~~~~~~~~~
    // ---- Functions -----------~~~~~~~~~~~~~~~~~~~~
    // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    
    
    char* srcServerIPs() {								// Get the server list
    
    	SOCKET WebSocket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
    
    	struct hostent *WebHost;									// Get the web server external IP
    	WebHost = gethostbyname(WEBSITE);
    
    	SOCKADDR_IN SockAddr;										// Connect to the web server
    	SockAddr.sin_port	= htons(80);
    	SockAddr.sin_family	= AF_INET;
    
    	SockAddr.sin_addr.s_addr = *((unsigned long*)WebHost->h_addr);
    	connect(WebSocket, (SOCKADDR*)(&SockAddr), sizeof(SockAddr));
    
    	send(WebSocket, REQUEST, strlen(REQUEST), 0);				// Send the request
    
    
    	char* Data = new char[(17*(MAXSERVERS))+1];
    	recv(WebSocket, Data, 4, 0);								// Skip HTTP headers...
    	for (;;) {
    
    		Data[0] = Data[1];
    		Data[1] = Data[2];
    		Data[2] = Data[3];
    
    		recv(WebSocket, &Data[3], 1, 0);
    
    		if (Data[0] == '\r' && Data[1] == '\n'
    		&&	Data[2] == '\r' && Data[3] == '\n')
    			break;
    
    	}
    
    	U16 DataLen = recv(WebSocket, Data, (17*(MAXSERVERS)), 0);	// Get the IP data
    	Data[DataLen] = '\0';
    
    	shutdown(WebSocket, 2);
    	closesocket(WebSocket);
    	return Data;
    
    }
    
    void srcGetServerIP() {
    
    	U8 IPNum = 0;
    	U16 Pos = 0;
    
    	while (ServerIPList[Pos++] != '\0') {
    		while (ServerIPList[Pos++] != '|');
    			++IPNum;
    	}
    
    	Pos = 0;
    	U8 IP, IPPos = 0;
    	char IPData[MAXSERVERS][17];
    
    	for (IP = 0; IP < IPNum; ++IP) {
    
    		IPPos = 0;
    		while (ServerIPList[Pos] != '|')
    			IPData[IP][IPPos++] = ServerIPList[Pos++];
    
    		IPData[IP][IPPos] = '\0';
    
    	}
    
    
    	HMENU hPopupMenu = CreatePopupMenu();
    	InsertMenu(hPopupMenu, 0, MF_BYPOSITION | MF_DISABLED, 0, "Select Server");
    	InsertMenu(hPopupMenu, 0, MF_BYPOSITION | MF_SEPARATOR, 0, "");
    
    	for (IP = 0; IP < IPNum; ++IP)
    		InsertMenu(hPopupMenu, 0, MF_BYPOSITION | MF_STRING, IP, IPData[IP]);
    
    	U8 Serv = TrackPopupMenu(hPopupMenu, TPM_RETURNCMD, CW_DEFAULT, CW_DEFAULT, 0, hWnd, NULL);
    
    	for (Pos = 0; Pos < 17; ++Pos)
    		ServerIP[Pos] =	IPData[Serv][Pos];
    
    }
    
    
    void srcAddMessage(LPCSTR Message) {					// Add a message to the List
    
    	SendMessage(GetDlgItem(hWnd, LISTID), EM_SETSEL, 0xFFFF, 0xFFFF);
    	SendMessage(GetDlgItem(hWnd, LISTID), EM_REPLACESEL, true, (LPARAM)Message);
    	SendMessage(GetDlgItem(hWnd, LISTID), EM_REPLACESEL, true, (LPARAM)"\r\n");
    
    }
    
    void srcSendMessage(LPCSTR Message) {					// Send a message to the Server
    
    	send(ServSock, Message, strlen(Message), 0);
    
    }
    
    
    // --------------------
    
    void srcClientStep() {
    
    	for (;;) {
    
    		static U8 Pos = 0;
    
    		if (!(++Pos % 52))								// Ping the server (let him know we're here)
    			send(ServSock, "\n\r", 2, 0);
    
    		char Msg[256];
    		int Len = recv(ServSock, Msg, 256, 0);
    
    		if (Len > 0) {
    			Msg[Len] = '\0';
    			srcAddMessage(Msg);
    		}
    
    		Sleep(5);
    
    	}
    
    }
    
    void srcClientStart() {
    
    	WSADATA wsaData;
    	WSAStartup(MAKEWORD(2,2), &wsaData);
    
    	ServerIPList = srcServerIPs();
    	ServSock = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
    
    	srcGetServerIP();		// "Select a Server"
    
    
    	SOCKADDR_IN SockAddr;
    	SockAddr.sin_port	= htons(PORT);
    	SockAddr.sin_family	= AF_INET;
    
    	SockAddr.sin_addr.s_addr = inet_addr(ServerIP);
    	connect(ServSock, (SOCKADDR*)(&SockAddr), sizeof(SockAddr));
    
    
    	u_long iMode = 1;		// Don't block
    	ioctlsocket(ServSock, FIONBIO, &iMode);
    
    	// Create the thread
    	CreateThread(0, 0, (LPTHREAD_START_ROUTINE)srcClientStep, 0, 0, 0);
    
    }
    
    void srcClientEnd() {
    
    	delete[] ServerIPList;
    
    	shutdown(ServSock, 2);
    	closesocket(ServSock);
    	WSACleanup();
    
    }

    Server code:

    // ---------------------------------
    // ---- Type defines ----------------
    
    typedef unsigned long	U32;
    typedef unsigned short	U16;
    typedef unsigned short	U8;
    
    typedef signed long		S32;
    typedef signed short	S16;
    typedef signed short	S8;
    
    
    
    // -----------------------------------
    // ------ Defines ---------------------
    
    #define WEBSITE			"masterserver.x10host.com"		// Full website URL, withouth HTTP (raises exe size)
    #define WEBPAGE			"/Server.php"					// The page of the Server Script (proceed with '\')
    #define IPFILE			"/IPLIST"
    
    //#define REQUEST			"GET " WEBSITE IPFILE " HTTP/1.1\r\n\r\n\r\n"
    #define REQUEST			"GET " IPFILE " HTTP/1.1\r\nHost: " WEBSITE "\r\n\r\n"
    
    #define WINTITLE		"Server Program"
    #define WINCLASS		"SRRCLASS"
    
    #define WINWIDTH		384
    #define WINHEIGHT		512
    
    #define PORT			7171
    
    #define MAXCLIENTS		16
    #define TIMEOUT			1024							// Ticks till timeout
    
    #define EDITID			200								// The edit control ID
    #define LISTID			201								// The listbox control ID
    
    
    // -----------------------------------
    // ------ Server Messages -------------
    
    #define cAddIP			0			// Send this to add an IP to the list
    #define cRemIP			1			// Send this to remove an IP from the list
    #define cGetIPs			2			// Send this to get a list of all Server IPs
    
    
    
    // ------------------------------------
    // ----- Global Variables --------------
    
    NOTIFYICONDATA	SysIcon;
    HWND			hWnd;
    
    SOCKET ListenSocket;
    SOCKADDR_IN ServerAddr;
    
    
    char* MyIP;							// My External IP
    
    
    U8 ClientNum = 0;					// Total clients
    SOCKET ClientSock[MAXCLIENTS];		// Client sockets
    U32 ClientTime[MAXCLIENTS];			// Time since last ping (for timeout)
    
    
    
    // ----------------------------~~~~~~~~~~~~~~~
    // ---- Functions -----------~~~~~~~~~~~~~~~~~~~~
    // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    
    
    char* srcWebPost(char Website[], char Webpage[], char Request[], U16 RetLen) {
    	// Sends an HTTP Post request ot the Website, on the Webpage with the POST Data...
    
    	SOCKET WebSocket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
    
    	struct hostent *WebHost;
    	WebHost = gethostbyname(Website);
    
    	SOCKADDR_IN SockAddr;
    	SockAddr.sin_port	= htons(80);
    	SockAddr.sin_family	= AF_INET;
    
    	SockAddr.sin_addr.s_addr = *((unsigned long*)WebHost->h_addr);
    	connect(WebSocket, (SOCKADDR*)(&SockAddr), sizeof(SockAddr));
    
    
    	char PostRequest[1024];
    
    	sprintf(PostRequest,
    		"POST %s HTTP/1.1\r\n"
    		"Host: %s\r\n"
    		"Content-Length: %hu\r\n"
    		"Content-Type: application/x-www-form-urlencoded\r\n"
    		"\r\nD=%s\0",
    		Webpage, Website,
    		strlen(Request)+2, Request
    	);
    
    	send(WebSocket, PostRequest, strlen(PostRequest), 0);
    
    
    	// Get return data ----------
    
    	char* Data = new char[RetLen];
    	recv(WebSocket, Data, 4, 0);
    
    	for (;;) {							// Skip HTTP headers...
    
    		Data[0] = Data[1];
    		Data[1] = Data[2];
    		Data[2] = Data[3];
    
    		recv(WebSocket, &Data[3], 1, 0);
    
    		if (Data[0] == '\r' && Data[1] == '\n'
    		&&	Data[2] == '\r' && Data[3] == '\n')
    			break;
    
    	}
    
    	U16 DataLen = recv(WebSocket, Data, RetLen, 0);
    	Data[DataLen] = '\0';	// Return the data...
    
    	shutdown(WebSocket, 2);
    	closesocket(WebSocket);
    	return Data;
    
    }
    
    
    void srcBalloonTip(LPCSTR Tip) {
    
    	NOTIFYICONDATA IconData = {0};
    	memcpy(IconData.szInfo, Tip, strlen(Tip));
    
    	IconData.uTimeout = 5000;	 // Display time (VISTA AND EARLIER ONLY)
    
    	IconData.cbSize	= sizeof(IconData);
    	IconData.hWnd	= hWnd;
    	IconData.uFlags	= NIF_INFO;
    	IconData.uID	= 0;
    
    	Shell_NotifyIcon(NIM_MODIFY, &IconData);
    
    }
    
    void srcAddMessage(LPCSTR Message) {					// Add a message to the List
    
    	SendMessage(GetDlgItem(hWnd, LISTID), EM_SETSEL, 0xFFFF, 0xFFFF);
    	SendMessage(GetDlgItem(hWnd, LISTID), EM_REPLACESEL, true, (LPARAM)Message);
    	SendMessage(GetDlgItem(hWnd, LISTID), EM_REPLACESEL, true, (LPARAM)"\r\n");
    
    }
    
    void srcSendMessage(LPCSTR Message) {					// Sends a message to the clients
    
    	for (U8 Client = 0; Client < ClientNum; ++Client)
    		send(ClientSock[Client], Message, strlen(Message), 0);
    
    	srcAddMessage(Message);								// Add a message to the list display
    
    }
    
    
    void srcKickClient(const U8 ClientID) {					// Removes a client form the list (from eg timeout)
    
    	--ClientNum;
    
    	srcBalloonTip("Client left!");
    	srcSendMessage("** Client Left **");
    
    	shutdown(ClientSock[ClientID], 2);
    	closesocket(ClientSock[ClientID]);
    
    	ClientTime[ClientID] = ClientTime[ClientNum];
    	ClientSock[ClientID] = ClientSock[ClientNum];
    
    }
    
    
    void srcAddClients() {									// Checks for new Clients, and accepts them
    
    	u_long iMode = 1;	// Don't block
    	ioctlsocket(ClientSock[ClientNum], FIONBIO, &iMode);
    
    	ClientSock[ClientNum] = accept(ListenSocket, NULL, NULL);
    
    	if (ClientSock[ClientNum] != SOCKET_ERROR) {
    
    		char Msg[] = "** Client Enters **";
    		send(ClientSock[ClientNum], Msg, strlen(Msg), 0);
    
    		ClientTime[ClientNum++] = 0;
    		srcBalloonTip("New Client!");
    
    	}
    
    }
    
    void srcMsgClients() {			// Gets and sends messages to the Clients
    
    	char Message[256];
    
    	for (U8 Client = 0; Client < ClientNum; ++Client) {
    
    		int Len = recv(ClientSock[Client], Message, 256, 0);
    
    		if (Len < 1) {										// Client didn't send anything...
    
    			if (++ClientTime[Client] == TIMEOUT)
    				srcKickClient(Client);
    
    			return;
    
    		}
    
    
    		if (Message[0] == '\n' && Message[1] == '\r') {		// The Client told me he is still here!
    
    			ClientTime[Client] = 0;
    
    		} else {											// Client sent a message!
    
    			Message[Len] = '\0';
    			ClientTime[Client] = 0;
    
    			srcSendMessage(Message);
    			srcBalloonTip(Message);				// Preview message
    
    		}
    
    	}
    
    }
    
    
    
    
    // ----------- Server Step -----------------
    // --------------------------------------------
    
    void srcServerStep() {								// Main server program, runs about 1000x a sec
    
    	if (ClientNum < MAXCLIENTS)
    		srcAddClients();
    
    	srcMsgClients();
    
    }
    
    
    
    // ----------- Server Start ---------------
    // -------------------------------------------
    
    void srcServerStart() {
    
    	WSADATA wsaData;
    	WSAStartup(MAKEWORD(2,2), &wsaData);
    
    	MyIP = srcWebPost("api.externalip.net", "/ip/", "", 16);
    
    	char SendBuf[32];
    	sprintf(SendBuf, "%hhu|%s", cAddIP, MyIP);			// Send the server your IP
    	srcWebPost(WEBSITE, WEBPAGE, SendBuf, 0);
    
    	ListenSocket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
    
    	if (ListenSocket == INVALID_SOCKET)
    		exit(0);
    
    	ServerAddr.sin_family = AF_INET;
    	ServerAddr.sin_port = htons(PORT);
    	ServerAddr.sin_addr.s_addr = htonl(INADDR_ANY);
    
    	if (bind(ListenSocket, (SOCKADDR *)&ServerAddr, sizeof(ServerAddr)) == SOCKET_ERROR)
    		exit(0);
    
    	if (listen(ListenSocket, 5) == SOCKET_ERROR)
    		exit(0);
    
    
    	u_long iMode = 1;	// Don't block
    	ioctlsocket(ListenSocket, FIONBIO, &iMode);
    
    
    	srcBalloonTip("Server is Running...");
    	srcAddMessage("** Server Started **");
    
    }
    
    
    // ----------- Server End ------------------
    // -------------------------------------------
    
    void srcServerEnd() {
    
    	char SendBuf[32];
    	sprintf(SendBuf, "%hhu|%s", cRemIP, MyIP);		// Remove my IP from the list
    	srcWebPost(WEBSITE, WEBPAGE, SendBuf, 0);
    
    	srcBalloonTip("Shutting Down...");				// Let the user know it shut down OK
    	Sleep(2000);
    
    	Shell_NotifyIcon(NIM_DELETE, &SysIcon);			// Remove the Systray Icon
    	delete[] MyIP;									// Free my IP
    
    	WSACleanup();
    
    }

    What is wrong?



    • Edited by Turda Alexander Monday, June 24, 2013 9:32 PM
    • Moved by Elegentin Xie Tuesday, June 25, 2013 6:51 AM from Visual C++, to a more appropriate forum
    Monday, June 24, 2013 8:55 PM

All replies

  • Hi,
    Welcome to the MSDN forum.
    Based on your description, your problems is about Winsock, I’d move the thread to Windows Desktop Winsock Kernel (WSK) ,since we here only discuss general native C++ problems on developing.
    Thanks for your understanding.
    Regards,


    Elegentin Xie
    MSDN Community Support | Feedback to us
    Develop and promote your apps in Windows Store
    Please remember to mark the replies as answers if they help and unmark them if they provide no help.

    Tuesday, June 25, 2013 6:50 AM