Click here to Skip to main content
15,880,503 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
I've just recently started playing around with winsock. I have however ran into a bit of a snag. How would one using the code below keep the client running while it accepts multiple transmissions from the server. I've tried to fix this myself however I am uncertain on how to do so.
C++
int client(string ip)
{
	// Initialise Winsock
	WSADATA WsaDat;
	WSAStartup(MAKEWORD(2,2),&WsaDat);
	
	SOCKET Socket=socket(AF_INET,SOCK_STREAM,IPPROTO_TCP);
	struct hostent *host;

	// Socket stuff
	SOCKADDR_IN SockAddr;
	SockAddr.sin_port=htons(8888);
	SockAddr.sin_family=AF_INET;
	SockAddr.sin_addr.s_addr= inet_addr(ip.c_str());

	if(connect(Socket,(SOCKADDR*)(&SockAddr),sizeof(SockAddr))!=0)
	{
		std::cout<<"Failed to establish connection with server\r\n";
		WSACleanup();
		system("PAUSE");
		return 0;
	}

	// Display message from server
	char *data = new char[1001];
	memset(data,0,1000);

	int inDataLength=recv(Socket,data,1000,0);
	cout << data << endl;

	shutdown(Socket,SD_SEND);
	closesocket(Socket);
	WSACleanup();
	system("PAUSE");
	return 0;
}
Posted

Multithreading: usually blocking I/O calls are handled in separate threads.
 
Share this answer
 
Create a loop that continues to sit on a recv call. Terminate the loop only when you receive a quit call from the server. However, your code is not very logical. The usual sequence would be:
connect
LOOP:
    send a message to the server
    receive a response
    if not "quit" THEN GOTO LOOP

close socket
terminate
 
Share this answer
 
Comments
Member 10657083 16-Dec-15 5:28am    
Ok but how would that look in with this snipet. How would you keep the client in this situation running and ready to receive data from the server.

int inDataLength=recv(Socket,data,1000,0);
cout << data << endl;
Richard MacCutchan 16-Dec-15 5:47am    
It would look just the same, the recv call is the second statement inside the loop pseudo code above.
Member 10657083 16-Dec-15 9:14am    
The Answer was right in front of me thank you.

Full code for future reference should someone need it.
http://pastebin.com/r7Up00A3
Richard MacCutchan 16-Dec-15 9:15am    
Yes, amazing what you can find with a little Googling.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900