GIDForums  

Go Back   GIDForums > Computer Programming Forums > C++ Forum
User Name
Password
Register FAQ Members List Calendar Search Today's Posts Mark Forums Read
 
 
Thread Tools Search this Thread Rate Thread
  #1  
Old 24-Nov-2011, 11:30
pma07pg pma07pg is offline
New Member
 
Join Date: Nov 2011
Posts: 3
pma07pg is on a distinguished road
Angry

Winsock Application Trouble


Hey, I am in desperate need of help.

I have to write a program using winsock with one serve and multiple clients. The user defines how many clients and then each client should display and animation one after another.

At the moment I have a working server which will connect up to five clients. However, I am having EXTREME difficulty to get any further than this point.

My Server file is as follows
CPP / C++ / C Code:
#include <iostream>
#include <winsock2.h>

#include<conio.h> 

#pragma comment(lib, "ws2_32.lib")	// Use this library whilst linking - contains the Winsock2 implementation.

int clients(0); 
SOCKET sockets[5];

float gPosition = 23.78;

int main()
{
	WSADATA WsaDat;

	// Initialise Windows Sockets
	if (WSAStartup(MAKEWORD(2,2), &WsaDat)!=0){

		std::cout << "WSA Initialization failed!\r\n";
		WSACleanup();
		return 0;
	}
	
	std:: cout << "\t\tNetwork App\n\nHow many clients?";
	std::cin >> clients;

	while(clients < 1 || clients > 5){
		
		std:: cout << "\n\nHow many clients";
		std::cin >> clients;
	}

	// Create a unbound socket.
	SOCKET Socket = socket(AF_INET,SOCK_STREAM, IPPROTO_TCP);
	
	if (Socket == INVALID_SOCKET){

		std::cout << "Socket creation failed.\r\n";
		WSACleanup();
		return 0;
	}

	// Now, try and bind the socket to any incoming IP address on Port 8888.
	SOCKADDR_IN serverInf;
	serverInf.sin_family		= AF_INET;
	serverInf.sin_addr.s_addr	= INADDR_ANY;
	serverInf.sin_port			= htons(8888);

	if (bind(Socket, (SOCKADDR*)(&serverInf), sizeof(serverInf)) == SOCKET_ERROR){

		std::cout << "Unable to bind socket!\r\n";
		WSACleanup();
		return 0;
	}

	SOCKET TempSock = SOCKET_ERROR;
	int clientsRemaining = clients;

	while (clientsRemaining > 0)
	{

		listen(Socket,1);

		TempSock = SOCKET_ERROR;

		while (TempSock == SOCKET_ERROR)

		{
			std::cout << "Waiting for " << clientsRemaining << " client(s)...\r\n";
			TempSock = accept(Socket,NULL,NULL);
	    }
		
		std::cout << "Client connected!\n\n";

		sockets[clients-clientsRemaining] = TempSock;
		
		--clientsRemaining;

	
	}
	std::cout << "Application has started!\n\n";

	
	char char_stream[1000];

	sprintf_s(char_stream, "%f", gPosition); //Convert float to char

	for (int i = 0; i < clients; ++i)
	{
	
		char_stream[0] = (i + 1); //client ID
		send(sockets[i], char_stream, strlen(char_stream), 0); //Send informations to client
	}

	// Shutdown our socket
	shutdown(Socket, SD_SEND);

	// Close our socket entirely
	closesocket(Socket);

	// Cleanup Winsock
	WSACleanup();

	while (!_kbhit());

	return 0;
}

My Client file contains a whole bunch of direct x stuff so I won't include all of it. The main gist of it is this:

CPP / C++ / C Code:
int WINAPI WinMain(HINSTANCE hInst, HINSTANCE, LPSTR, int)
	{
		// Register the window class
		WNDCLASSEX wc = {sizeof(WNDCLASSEX), CS_CLASSDC, MsgProc, 0L, 0L,
						 GetModuleHandle(NULL), NULL, NULL, NULL, NULL,
						 "Translation Example", NULL};
		RegisterClassEx(&wc);

		// Create the application's window
		HWND hWnd = CreateWindow( "Translation Example", "Translation Example",
								  WS_OVERLAPPEDWINDOW, 100, 100, 500, 500,
								  GetDesktopWindow(), NULL, wc.hInstance, NULL);

		// Initialise Winsock
		WSADATA WsaDat;			
		struct hostent *host;
		
		if (WSAStartup(MAKEWORD(2,2), &WsaDat) != 0)
		{
			//std::cout << "Winsock error - Winsock initialization failed\r\n";
			WSACleanup();
			//return 0;
		}
	
		// Create our socket
		SOCKET Socket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
		if (Socket == INVALID_SOCKET)
		{
				//std::cout << "Winsock error - Socket creation Failed!\r\n";
				WSACleanup();
				//return 0;
		}
	
		// Change this to point to server, or ip address...

		if ((host = gethostbyname("localhost")) == NULL)   // In this case 'localhost' is the local machine. Change this to a proper IP address if connecting to another machine on the network.
		{
				//std::cout << "Failed to resolve hostname.\r\n";
				WSACleanup();
				//return 0;
		}

					
		// Setup our socket address structure.
		SOCKADDR_IN SockAddr;
		SockAddr.sin_port		 = htons(8888);	// Port number
		SockAddr.sin_family		 = AF_INET;		// Use the Internet Protocol (IP)
		SockAddr.sin_addr.s_addr = *((unsigned long*)host -> h_addr);
		

			// Attempt to connect to server...
		if (connect(Socket, (SOCKADDR*)(&SockAddr), sizeof(SockAddr)) != 0)
		{
				//std::cout << "Failed to establish connection with server\r\n";
				WSACleanup();
				//return 0;
		}			
	
		char buffer[1000];
		memset(buffer, 0, 999);

		int inDataLength = recv(Socket, buffer, 1000, 0);

		//int a = WSAGetLastError();
	
		clientID = buffer[0];
	
		for (int i = 0; i < 999; ++i)
		{
			buffer[i] = buffer[i+1];
		}
		buffer[999] = 0;

		// Initialize Direct3D
		if (SUCCEEDED(SetupD3D(hWnd)))
		{

			// Create the scene geometry
			if (SUCCEEDED(SetupGeometry()))
			{
				// Show the window
				ShowWindow(hWnd, SW_SHOWDEFAULT);
				UpdateWindow(hWnd);

				// Enter the message loop
				MSG msg;
				ZeroMemory(&msg, sizeof(msg));
				while (msg.message != WM_QUIT)
				{
					if (PeekMessage(&msg, NULL, 0U, 0U, PM_REMOVE))
					{
						TranslateMessage(&msg);
						DispatchMessage(&msg);
					}
					else
						Render();
				}
			}
		}
	

	// Shutdown our socket.
	shutdown(Socket, SD_SEND);

	// Close our socket entirely.
	closesocket(Socket);

	// Cleanup Winsock.
	WSACleanup();

	CleanUp();

    UnregisterClass("Translation Example", wc.hInstance);
    return 0;
}

On my machine the code works fine and will display a cube moving across each window with a respective client number on each window.

I have an idea of how to complete this task but do not know how to implement it. Any help would be massively appreciated. I can also post/email the full code to anyone who wishes to see it and help!

Many thanks,
Pete
  #2  
Old 24-Nov-2011, 13:31
Mexican Bob's Avatar
Mexican Bob Mexican Bob is offline
Regular Member
 
Join Date: Mar 2008
Location: Chicxulub, Yucatán
Posts: 686
Mexican Bob is a jewel in the roughMexican Bob is a jewel in the roughMexican Bob is a jewel in the roughMexican Bob is a jewel in the rough

Re: Winsock Application Trouble


1: this code is not C++, at best, it is C with some C++
2: there is no conio.h in either standard C or standard C++
3: the Win32 API is a C library, this is a platform-agnostic forum area (try the Windows-specific sections)
4: Sockets are not part of the C or C++ standards

That being said, why are you telling us that you have an array of 5 sockets? Is that the maximum number that you have to support?

If you still need/want help, perhaps I can fire up a Windoze box and lend a hand...however, you may want to READ THE GUIDELINES and then tell us where and/or what you're having problems with...


MxB
  #3  
Old 24-Nov-2011, 15:13
pma07pg pma07pg is offline
New Member
 
Join Date: Nov 2011
Posts: 3
pma07pg is on a distinguished road

Re: Winsock Application Trouble


Hey Mexican Bob,

I am using Visual Studio 2010 and that does have conio.h which allows for _kbhit().

I was thinking about using classes etc for dealing with threads and stuff which will be c++.

The max number of sockets is as many as I wish, that's just the number I've chosen to use. It's easier as I want to display the animations on a local machine.

Specifically, I need to have the client windows playing the single animation sequentially, ie when it leaves one screen it appears on the next.

At the moment I have three clients that connect with the server. The clients all begin playing an animation as soon as the user defined number of clients have been created which in my case is just opening the client.exe file.
If you have any ideas that would be really helpful!

Cheers,
Pete
  #4  
Old 24-Nov-2011, 15:37
Mexican Bob's Avatar
Mexican Bob Mexican Bob is offline
Regular Member
 
Join Date: Mar 2008
Location: Chicxulub, Yucatán
Posts: 686
Mexican Bob is a jewel in the roughMexican Bob is a jewel in the roughMexican Bob is a jewel in the roughMexican Bob is a jewel in the rough

Re: Winsock Application Trouble


Quote:
Originally Posted by pma07pg
Specifically, I need to have the client windows playing the single animation sequentially, ie when it leaves one screen it appears on the next.

What you need to do is stop acting like you already know what you're doing and start acting like you're explaining it to someone who has no idea what you're doing. What you said makes no sense at all. Work with me...

"when it leaves" what is "it?" Are you trying to say that you want to create some number of windows and that you want a "frame" of your "animation" to display first on one window and then on the "next" one and then the "next one after that one" and so forth? What does "leaves one screen" mean? Does it ever "leave" one screen for another or entirely? What does "leave" mean?

Is there any likelihood that you're going to be able to spend a moment telling us what you actually want to accomplish?

Your context is all from within a "Winsock" related application; is the "trouble" at all with the sockets and/or connections or is the application simply a sockets-based app and none of the sockets code is part of the issue? Or, something else? Such as, when I make a socket connection to the server, it streams the "next frame" in an animation (looping?) and the client receives the data and displays it until the next frame is received and then refreshes its drawing region with the new data?

Any chance you're going to spew forth something that means something tangible? Start like we don't know how to read your mind. Then continue on like there is no such thing as "conio.h" in standard C or standard C++...whether your particular world has it or not. Some of us are obviously not from your world, since we don't speak your language or read minds the way that you do...

If you *still* want some help, read the GUIDELINES for posting help requests and try again...



MxB
  #5  
Old 24-Nov-2011, 15:59
pma07pg pma07pg is offline
New Member
 
Join Date: Nov 2011
Posts: 3
pma07pg is on a distinguished road

Re: Winsock Application Trouble


Ok, I'll be as specific as possible. I want a ball to move from the left hand side of a window to the right. As the ball begins to leave the first window, ie the client, the ball starts to move onto the second window. Therefore seemingly moving across a single screen although moving across up to five client Windows.

This process must be completed using winsock.

At the moment the code I have written connects up to 5 clients with one server. Once the clients have been created an image moves from the left of all screens to the right of all screens simultaneously. My server doesn't tell any of the clients when to draw the image nor is there any relation of location to the server by the client.
  #6  
Old 25-Nov-2011, 03:54
Mexican Bob's Avatar
Mexican Bob Mexican Bob is offline
Regular Member
 
Join Date: Mar 2008
Location: Chicxulub, Yucatán
Posts: 686
Mexican Bob is a jewel in the roughMexican Bob is a jewel in the roughMexican Bob is a jewel in the roughMexican Bob is a jewel in the rough

Re: Winsock Application Trouble


Quote:
Originally Posted by pma07pg
Ok, I'll be as specific as possible.

None of this is meaningful in the least...nor is it "specific." It is a hodge-podge of "noise" using mixed terms, incomplete information and something that is coupled to your brain, but can't seem to find its way to your finger tips.

What you seem to need to do here, is quit trying to tell us what you want to see on "screen" (whether you want to use "screens" or whatever term to describe it). I personally could care less at this point, particularly since we're assuming that ALL of that is happening in the code that you have NOT provided.

What you need to do is describe the relationship between your CLIENT and your SERVER...other than the underlying Windows socket connection. What happens when you make a connection? Do you "chat" between the two? Do you have a "dialog" (not to be confused with a Dialog wndclass window in Windows) between the client and server? What "messages" do you send between them that aims to do the work of "synchronizing" the features that they're capable of providing? What features does a "client" provide that "interacts" with the server in some meaningful way? Does the server "tell a story" and any client "listening" can "render" it accordingly to their implementation? Does the server "push" data to the client and the client simply "draws" it based on the "message type" or "data type" or some other "protocol?"

If you step away from your computer for a moment, and you listen at all to what you wrote, you will see that you haven't said a thing about what happens over the socket connection, just that you have to use it...and supposedly with some number of "clients" and a "single" server, whose physical location isn't necessarily local. That is a fairly common situation where one would use sockets, so it hasn't given us any real input other than there seems to be a justification for using sockets (other than you MUST).

If you are telling us that there are a known number of clients, and that you want to either send some data that is drawn by one or more clients OR that you want to send some data that, when received by a client, is some kind of "command" that tells them "draw a ball in location x, y" you need to TELL US what it is that you're really trying to accomplish...so that we can perhaps offer some kind of help with "code."

Let's say that we throw away everything that you've written in code for a moment. Let's say that we want to quit thinking about rendering and quit thinking about moving or a ball or whatever a "screen" is or isn't and how many clients are connected for a moment.

What is the relationship between the client and server? What data are you intending to send over the socket?

Can we break down this application to a much simpler one? Is there something that we can write in code that will help us to "explore" the implementation and be "characteristic" of what it is that we want to do, without having to do all of the work?

Let's say that we reduced the task to two "clients" and that we're going to endlessly send, from the server to the client an integer and that every second, we're going to increment that integer. The client will display the integer that the server sent. The first client will display the integer as sent by the server and the second client will display the integer as sent by the server, but add 1 to it (pre-increment it before displaying it). So, if both clients were connected and the server sent a '1' to both at or about the same time, client 1 would display a 1 and client 2 would display a 2. A second later, the server would send a 2 to both clients and then client 1 would display a 2 and client 2 would display a 3.

What we have here is a data stream coming from the server and then the clients act upon the stream, working with the data as appropriate based on their relationship to the server. We've taken a good bit of the complexity out of the server, which only accepts connections and sends the same data to every client. We've placed some responsibility in the clients to do something "interesting" with the data when they receive it, in this case, add a 0 to the integer if it is the first client and add a 1 to the integer if it is the second client...and so on, if we continue this thinking for multiple clients.

At some point, we have to being wondering how we're going to "know" whether the client is the 3rd or 5th or 1827th "connected" to the server and whether or not we're doing the "right thing" when we receive data from the server. We could add more responsibility to the server so that it sends different data to every client. We could change our design so that the client is "dumb" and just displays whatever integer we send it...and the server is responsible for making sure that client 1 gets a 1 and that client 2 gets a 2, if that is what we want to "see on screen."

Of course, we can put all sorts of data "on the wire" (of course, this term is old now that we live in a "wireless" age) and not just a single integer value. We can send to clients a "stack" of "images" and a time base and a sequencing order that tells the client what to do in a very granular level, such as a "scripted" set of commands:

command:value
SET BACKGROUND COLOR:BLACK
CLEAR TO BACKGROUND COLOR:NOW
WAIT SECONDS:THREE
DRAW IMAGE:ZERO
WAIT SECONDS:ONE
DRAW IMAGE:ONE
WAIT SECONDS:TEN
DRAW IMAGE:TWO
WAIT MILLISECONDS:250
DRAW IMAGE:THREE
WAIT MILLISECONDS:250
...

We can be as low-level or high-level as we desire:

PLAY ANIMATION:NOW


The question is what do you want to send from the server, receive by the client and how does that relationship accomplish the "work" you desire?

Are you going to have multiple message types being sent from the server, such as what color to display on the background or (if I understand you at all), what image to display "simultaneously" and what image (or state) to display "independently?"

Maybe you're further along then you seem, but maybe implementing a lower set of capability first will be helpful? Perhaps try to "render" the integers? Imagine mapping some "result" to some integer?

For example, let's say that you wanted to model a traffic light that has only two states, red and green...and that you have two traffic lights. One for east-west bound traffic and the other for north-south bound traffic. Let's say that you wanted only one to be green at any given time and that the other would be red whenever the other is green. What would you send between the two of them if there was no server? What would you send from the server to each of them, if there is a server and they are the clients?

Can you distill your problem, with your 5 clients, into a set of known states that they must transition from/to? Like the traffic light, we can say that we must transition from red to green and from green to red. Those are two states and we can represent them with a single bit. In code, we might simply initialize to red (safe state) and then wait forever until we're told to transition or "toggle" state from red to green.

Take a moment to consider what I've spent my time describing in this response. What is a "screen" and what does "move" mean are terms you've decided to use that do nothing more than confuse things. Please do not reply with the same broken noise over and over again. If you want to know how to get something "on screen" to "move," throw the monitor as hard and fast as you can in any direction...the "screen" will likely "move." Obviously, this "for effect" methodology works much better with notebook computers, since they fly better without wires attached and they better illustrate the futility of spewing forth useless terms when you have to go retrieve them after throwing them across the room. Was it the "client" or "server" code being "debugged" in that case?


MxB
 


Thread Tools Search this Thread
Search this Thread:

Advanced Search
Rate This Thread
Rate This Thread:

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

vB code is On
Smilies are On
[IMG] code is On
HTML code is Off
Forum Jump

Similar Threads
Thread Thread Starter Forum Replies Last Post
MobileAuthorize - Free Credit Card Application for Smart Phones salemanager eCommerce / Merchant Account Forum 0 14-Mar-2011 04:43
The specified CGI application misbehaved by not returning a complete set of HTTP head bacchus MySQL / PHP Forum 6 16-Jul-2007 21:12
[PROGRAM] Winsock Programming Max Payne MS Visual C++ / MFC Forum 1 09-Mar-2007 00:38
Visual C++ 6.0 trouble LuciWiz MS Visual C++ / MFC Forum 3 02-Aug-2004 06:40
Having trouble trying to format C: Nickster64 Computer Software Forum - Windows 2 27-Jul-2004 07:31

Network Sites: GIDNetwork · GIDApp · GIDBlog · Learning Journal by J de Silva, The

All times are GMT -6. The time now is 09:28.


vBulletin, Copyright © 2000 - 2018, Jelsoft Enterprises Ltd.