Winsock functions lock/stall up program

Pages: 12
i put the winsock code in a seperate function and called it from inside winmain after the window is declared. It starts the window up then shows a loading icon (the sand timer) and doesn't lock up until i hit a key that sends
a message to the loop. But i can move the mouse around...its only when i click the mouse that it stops responding...but the fact still remains is it doesn't perform past the winsock code...

Edit: I commented out the listen function and compiled it and i was able to play the game...it rendered the opengl code and i could move around in the game. Then i left the listen function uncommented out and commented out the accept function and it compiled and ran and that is the last function in the winsock code. So it is the waiting to accept the client that is locking up my winsock code (I'm assuming because i have no clients for my server code to actually accept yet). But the only way i know of to have it run is if i actually have a client software compiled and have a request waiting to be accepted. But if i dont have one then i can't proceed in the program. what if i want to run my program without accepting sockets. How can i skip the accepting sockets when i dont know whether or not there are sockets waiting to be accepted. If there are no sockets waiting to be accepted then i can just skip it and proceed with the program. How can i know when i have a socket that is waiting to be accepted...say i've listened for it then it is stored in inret...what value does it return whenever the listen function hears a socket? If i know that i can use
an if statement to skip the accept function based on whether or not there is actually a socket that is waiting to be accepted.

When i say it locks up i mean it shows a loading sign then the screen turn white and windows pops up a message saying "3dgame.exe" has stopped responding then gives me the option to force close or wait for it to respond. The only thing i can think of the reason it would lock up is because the if statements only process socket errors as you'll see in the code below. there is no else statements. The only other reason i think it would lock up is because i dont actually have clients sending requests so when it listens or tries to form or bind the client socket it just keeps on listening and listening.....but that doesn't make to much sense because if winsock only worked in programs when there was sockets to be bound there would be no way to run programs that perform tasks
outside of bound sockets (like when internet explorer is dormant and not sending data requests.) I copied the winsock code from a reputable site so it worked for them.

do you think i should put it in a function outside of winmain then call that function from winmain? Im thinking even if i did that it would still lock up. I dont know why this code is freezing up though. Could it be because i haven't put my computers (the server) info into the struct thats called in the functions? I dont think its the lack of a client.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
/***** We begin by initializing Winsock.  I put this code in The Winmain function before the window handle is made...and the window was never created.  Then i put it afterwards and the window was created however it never proceeded past the winsock code to my opengl code...meaning the winsock code is whats freezing up.  socket, listeningsocket and client structs are declared globally after the header includes (not in the winmain function...but thats not the source of the problem) ******/

/**** the following struct could not be included in my main file because it had already been defined in one of the included headers and the compiler told me it just redefines it when i add it in my code.  so i left it out so i could compile  
it 
struct sockaddr_in
{
  short sin_family;         // Protocol type
  u_short sin_port;         // Port number of socket
  struct in_addr sin_addr;  // IP address
  char sin_zero[8];         // Unused
}; ****/

//following goes in winmain function
{	
SOCKET theClient;
SOCKET listeningSocket;

WSAStartup(sockVersion, &wsaData);
	// Next, create the listening socket

	listeningSocket = socket(AF_INET,		// Go over TCP/IP
			         SOCK_STREAM,   	// This is a stream-oriented socket
				 IPPROTO_TCP);		// Use TCP rather than UDP
      
                 if (listeningSocket == INVALID_SOCKET)
	{
		nret = WSAGetLastError();		// Get a more detailed error
		ReportError(nret, "socket()");		// Report the error with our custom function
		WSACleanup();				// Shutdown Winsock
		return NETWORK_ERROR;			// Return an error value
	} 

	// Use a SOCKADDR_IN struct to fill in address information
	SOCKADDR_IN serverInfo;
	serverInfo.sin_family = AF_INET;
	serverInfo.sin_addr.s_addr = INADDR_ANY;	// Since this socket is listening for connections,

							// any local address will do

	serverInfo.sin_port = htons(8888);		// Convert integer 8888 to network-byte order
							// and insert into the port field
	// Bind the socket to our local server address
	nret = bind(listeningSocket, (LPSOCKADDR)&serverInfo, sizeof(struct sockaddr_in));

	if (nret == SOCKET_ERROR)
	{
		nret = WSAGetLastError();
		ReportError(nret, "bind()");
		WSACleanup();
		return NETWORK_ERROR; 
	} 
	// Make the socket listen
	nret = listen(listeningSocket, 10);		// Up to 10 connections may wait at any
							// one time to be accept()'ed
	if (nret == SOCKET_ERROR)
	{
		nret = WSAGetLastError();
		ReportError(nret, "listen()");
		WSACleanup();
		return NETWORK_ERROR;
	} 

	// Wait for a client

	
	theClient = accept(listeningSocket,
			   NULL,			// Optionally, address of a SOCKADDR_IN struct
			   NULL);			// Optionally, address of variable containing
							// sizeof ( struct SOCKADDR_IN )



	if (theClient == INVALID_SOCKET)
	{
		nret = WSAGetLastError();
		ReportError(nret, "accept()");
        WSACleanup();
        return NETWORK_ERROR;
	}
// Send and receive from the client, and finally,	

closesocket(theClient);
	closesocket(listeningSocket);
	// Shutdown Winsock

	WSACleanup();
}

void ReportError(int errorCode, const char *whichFunc)

{

   char errorMsg[92];					// Declare a buffer to hold

							// the generated error message

   

   ZeroMemory(errorMsg, 92);				// Automatically NULL-terminate the string



   // The following line copies the phrase, whichFunc string, and integer errorCode into the buffer

   sprintf(errorMsg, "Call to %s returned error %d!", (char *)whichFunc, errorCode);



   MessageBox(NULL, errorMsg, "socketIndication", MB_OK);
}   
     	  
Last edited on
Edit: im gonna have to use a non-blocking socket which is a bummer because the tutorials i am finding are not for windows and i dont have the libraries necessary yet. Below is kinda irrelevant unless you know a way to not block the program. the above code is blocking winsock which waits until the code is complete before returning....which im guessing is why my program locks up.
---------------------------------------------------------------------------------------------
okay i looked on the msdn and the accept function is a loop i guess. Any idea how i can control whether or not the accept function is called and not miss incoming connections. Or any idea how to break out of the accept loop. Or only have it called when there is a client heard on the listening socket. Im sure it returns once an actual socket is accepted if not you could never do anything on the socket if it kept listening and accepting sockets forever and ever and never exited the loop. There has to be an f'ing way. Listen() returns either 0 or an error but it returns 0 whether or not there is clients heard or not. So unless there is something i am unaware of there is no way to know if you can skip the accept function when there are actually no sockets heard. And if you call the accept functions it waits until i client is actually needing to be accepted...this is freaking impossible. Someone please explain this better for me....these tutorials didn't do a very good job of clarifying how to do anything with the code at all if you are stuck in a system loop from accept() forever.

what if you want the server to run other functions (accessing a database) besides the winsock code then do the winsock code later? or what if you want to actally do something with the data that is sent or received on the socket but not miss incoming connections?
Last edited on
Instead of using an asynchronous socket, you could put your socket accept/response in another thread.
If you cannot afford to miss new incoming connections then you need to have your primary thread except incoming connections and then launch other threads to handle the requests\processing from each connection. You need to use a loop to continuosly check for incomming connections, this is simular to the loop in WinMain that processes Windows messages by constantly calling the callback function while popping system messages off of the stack, it's the traditional way of not missing anything and it works pretty well. Don't worry about breaking from the "accept()" loop, as long as you are launching threads to process the connections then the system scheduler will take care of what get's processed and when.
Last edited on
yikes.....i haven't learned about threading yet. From what i here it is tough to have multiple threads/fibers synchronize correctly. But luckily it was on my list to learn. I'm gonna have to have multiple threads for my multiplayer game because there is no way i could send and recv data from 100's of players (thats assuming i get that many people to play) in multiple games with one thread and not have players see lag. Unless i pay to have a pretty fast server hold my server code.

do you know of any good threading tutorials?
Yes, syncronizing data across multiple threads can be difficult. So design your program in a way that minimizes the need to do this and your problem is solved. You'll see some people here going crazy with the need to synchronize a dozen pieces of input from as many or more live streams but these people are all mathematicians and\or physicists so they're used to their job not being easy.

As for actually launching seperate threads with Win32, there is a learning curve but it's not that difficult. Make sure you understand type casting and what a pointer actually is.
closed account (DSLq5Di1)
http://tangentsoft.net/wskfaq/articles/io-strategies.html

http://msdn.microsoft.com/en-us/library/ms738545#winsock.advanced_winsock_samples
http://johnnie.jerrata.com/winsocktutorial/#nonblockingandasynchronoussockets
http://www.win32developer.com/tutorial/winsock/winsock_tutorial_6.shtm
lol that third link is the tutorial i got this code from. I guess i thought i had reached the end before and never scrolled on past the first part of the tutorial to the asynchronous tutorial with non blocking sockets. I get the code but there is some stuff i have questions over. The code was kinda scant so i did not fully grasp it. It seems it uses the same libraries as the first as he did not mention any other header requirements different from the first or any other library requirements.

So i would just call the same function to read, write, accept and listen on each socket. This is server side code.
WSAAsyncSelect ( theSocket, hwnd, THERE_WAS_A_SOCKET_EVENT, FD_READ | FD_WRITE | FD_CONNECT | ... );

that is from the 3rd link you provided.

edit: yeah im not understanding how this function works. Is it used by itself or used with all the other code above for blocking sockets you just use this to create the socket as non blocking then use the same functions as with blocking sockets to send, recv, accept and listen???.

------------------------------------------------------------------------------------------------------------------------

could you more thouroughly explain how i would send data. I'm guessing this one function handles all the winsock workload beside actually initiating it. It says i have to call the function manually after each function but at the same time it leads me to beleive a flag is sent out whenever data is received ect....but is this flag sent out by itself (while the program is doing oher tasks) once the client sends data to server or is it only sent out after you call the function and the function sees there is data to be read. I wish there was more examples of the code in action so i could grasp it better.

also if it returns before a completed operation how do you ensure you dont miss incoming data or connections. When data is sent while the server is doing other tasks when you go to recv that data will it still be recvd even though it was sent while it was doing other tasks. Or would i have to initiate threads to keep recving...well even that would not work on non blocking sockets because it would return immediately since it is a non blocking socket. I feel like im making this more complicated then it really is lol.

and would i use the same code for the client side as above. He provided no different examples for client side code in non blocking socket so im guessing it is the same on client side as it is with blocking sockets....am i correct?
Last edited on
I haven't looked at the resources sloppy9 posted but I find this one does a great job:
http://www.codeproject.com/KB/IP/beginningtcp_cpp.aspx

You wouldn't use WSAAsyncSelect to send data; you would use it to listen in the background for incoming connection requests and incoming data.

You need to setup a WndProc which handles the socket event passed in to WSAAsyncSelect. The resource I posted gives a skeleton example of how to use this function.

Edit: Ah, I see this resource sloppy9 posted shows an example as well:
http://johnnie.jerrata.com/winsocktutorial/#nonblockingandasynchronoussockets

yeah im not understanding how this function works. Is it used by itself or used with all the other code above for blocking sockets you just use this to create the socket as non blocking then use the same functions as with blocking sockets to send, recv, accept and listen???.

It is used together with blocking calls. Essentially, when you call WSAAsyncSelect, you tell it which window will handle the incoming socket events. For instance, the FD_READ event tells the handler to recv some data. You need to setup a WndProc as a handler. You could use an already-created Window and add the WSAAsyncSelect handling code to its WndProc, or, you could create an invisible window and write its WndProc to be a dedicated handler.

and would i use the same code for the client side as above. He provided no different examples for client side code in non blocking socket so im guessing it is the same on client side as it is with blocking sockets....am i correct?

If your client never recvs any data, then no worries. However, if the client does need to call recv for any reason then you have to make the same decision: Blocking read (probably not), or recv loop in another thread. I don't think WSAAsyncSelect can be used for a client socket, though I could be wrong.
Last edited on
I understand that you create a window to have a handle too.

edit: it seems from your link that he uses WSAA in client and server side. Maybe i misunderstood but he does state it runs in the background without interfering and the messages are sent based on client actions...(not having to call WSAA over and over on server side).

It seems as if he puts recv in a timer function so it doesn't stay blocking forever....but thats only if he is not using a WSAA socket. So i imagine a timer or WSAA socket could be used on client side also.

But my question is from your link the FD_READ message reads the data being recvd but how do you know who it is being recvd from...the socket is never handled in the event code as being the person it is recvd from. I imagine you would just have the socket a global socket and have a unique id assigned to it then in the FD_READ message have it get the socket and global identifier for that socket.

nvrmind there are more advanced functions called Sendto() and recvFrom(), that allow you to pick out individual users to send and recv from. I put the WSAA code in my program after listen to make the socket a listening socket then put the accept function in the FD_ACCEPT message case....is that the right message to put it in. Or would it go in FD_CONNECT. anyway it compiled and ran and it still rendered my 3d graphics of my game without locking up. So now i just need to make client side and get this motherfing game going multiplayer.

It seems as if WSAAsyncSelect merely creates the socket and tells it what flags it has. Then it works on an interrupt basis through windows messages without having to be called. But I dont see what the FD_SEND flag would be for if you dont send data through WSAA send. Or how these flags are even set if WSAAsyncSelect is not constantly called.

And yes client will be receiving data such as player coordinates and item coordinates as an example. I have heard that server code can also be client code (you put them together in same program)...so i imagine every instance of the program will behave as sever and client....but that may just be with blocking sockets.

The client should be able to recv data that is sent from server...that is the whole purpose of the server...as for whether or not it is blocking or not that can be determined by timer or by using WSAA on client side also...if it is allowed..or threading

If your still using the same blocking functions is it still going to block when you go to accept a socket or since you set the socket as Asychronous whenever you call the accept function or any other socket function it sees you are trying to accept or perform a task on a non blocking socket so it breaks immediately? thats what im understanding it as. You have to admit the tutorial on non blocking sockets was kind of vague.
Last edited on
edit: when using WSAAsyncSelect() what does the FD_CONNECT need to do or does it need to do any code like binding sockets in order to allow client to send the data on newly connnected sockets. it seems binding is only a server side function.

okay i got my server code and client code and each of them compiled and i got both the windows showing. Client was giving me errors connecting but its because i had server accepting connections on different port then client was attempting to connect on. I am running both client and server on same computer and im just connecting on local network ip address 127.0.0.1. after i changed ports to match on client and server i got client to run without errors however my client is not correctly sending data commands over winsock to server.

I have it set where when i press key A on client side it stores the letter A on server side. (its supposed to send the letter a when i push it)If nothing is sent then it pops up a message on client side saying nothing was sent ....which it is now doing. on server side i used WSAAsyncSelect() to set up socket as non blocking then put the recv() function in the FD_READ case in the swtich statement located in the callback windows procedure.

however for some reason it is not receving the data on server side or sending data from client side. Im guessing it has to do with my buffer on client and 'server side. or i am using WSAAsyncSelect wrong.

i used johnies tutorial from the link above posted by sloppy 9 then your tutorial from codeproject.com i just used the codeproject.com tutorial to learn where to place the WSAA function but the rest of my code resembles that from johnies tutorial. any idea what im doing wrong as to why it wont send data from client or recv on server side?
Last edited on
any idea what im doing wrong as to why it wont send data from client or recv on server side?

Firstly, is your server listening correctly? When you start your server app, once it binds its port and calls listen, go to the command line and type netstat -an. Your localhost and the port selected should show up there with the state "LISTENING".

Secondly, is data even being sent from the client? The send function returns the number of bytes sent. If there is an error, it returns SOCKET_ERROR.

I would try the above cases without using WSAAsyncSelect, to be sure that the networking is working at all. If it's not working, then it's a setup problem. If data is being sent from the client (and it is being read properly from the server) without using WSAAsyncSelect, then you can be sure that your use of asynchronous sockets is causing the problem. I haven't used asynchronous sockets before (the only Winsock program I wrote involved using blocking reads), so unfortunately I can't help much with its actual use. So far, I haven't found a nice, complete example on the web for their use. I could be misunderstanding them in some way.
Last edited on
Edit: ignore this message i figured it out on my own....however see below message.
Last edited on

i got it to send() without errors (although server didn't receive it but that is server code issue) but i had to put the code where it is not event based. i put the following code in Winmain after connect function on client side...before window is rendered.
1
2
3
4
5
6
7
8
9
10
11
12
13
 for (i=0; i<50; i++)
{
                         char buffer[2];
                         strcpy(buffer, "A");
                         nret=send(theSocket, buffer, strlen(buffer), 0);
                          if (nret==SOCKET_ERROR | nret<=0)
                         {
                                MessageBox(NULL, "Send() returned socket error.", "Socket Indication", MB_OK);
                                }
                         if (i>=0)
                         {
                                  MessageBox(NULL, "i has been incremented...data sent" , "Send loop notification", MB_OK);
                                  }


this pops up a message box and sends the letter A 50 times then the code continues and creates the window. But why does it give an error when i try to send from a message event...maybe i need to globally define everything. I put a while loop in the winmain function that receives messages then dispatches them as long as a wm_quit message is not posted. Then i put the send() function in the while loop and it sent data out from the while loop. My problem is when i initiate winsock in one function....then try to send data with send() from a different function my error code pops up saying "send() sent out no data." So it has to do with where i call the send function from.

i just realized i forgot both the macros below and i was using (wParam) in the callback procedure instead of (lparam) i have since added the below macros however the first macro is always giving me errors when called in the callback procedure. and i have no idea why it is...im guessing why thats why it never gets to the FD_READ case or the FD_ACCEPT case.
WSAGETSELECTERROR ( LPARAM lparam )
Determines if the socket has returned an error. Technically, this is not a function but a macro (you can really generate smalltalk at parties with this little factoid).
WSAGETSELECTEVENT ( LPARAM lparam )
Another useful macro defined in winsock2.h is WSAGETSELECTEVENT(), which is used to see exactly what the socket has done.

here is my code in callback message procedure it pops up 1,000's of the message boxes i told it to pop up when it gets an error...any idea why? if i block out the WSAGETSELECTERROR code it runs and client can connect and send data without errors...however everytime i send from client...server side gets flagged on FD_READ and does the code (below) but doesn't receive any of the data it was flagged to recv().
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
case MY_MESSAGE_NOTIFICATION: //Is a message being sent?

        {
            if ( WSAGETSELECTERROR ( lParam ) )

			{	// If an error occurred,
                MessageBox(NULL, "An error occured unable to initiate winsock", "socket indication", MB_OK);
				closesocket ( theClient );
				closesocket (listeningSocket);

				WSACleanup ();				// Shutdown Winsock

				return NETWORK_ERROR;

			} 
			switch ( WSAGETSELECTEVENT ( lParam ) )
			{	// What happened, exactly?
                case FD_CLOSE:
                     MessageBox(NULL, "Connection was aborted..client left", "socket indication", MB_OK);
                     break;
				case FD_READ:
                     char buffer[2];
                //Incoming data; get ready to receive
                nret = recv(theClient,buffer, strlen(buffer),	0);
                if (nret <= 0)
	            	{
			             MessageBox(NULL, "recv() returned nothing.", "socketIndication", MB_OK);
		              }
		              switch (buffer[0])
		              {
                       case 'A':
                       isMovingleft=true;
                       return 0;
                        }
                 return 0;
					// Receive data

				case FD_WRITE:

					// Write data

					break;
					
                case FD_ACCEPT:
                      theClient = accept(listeningSocket,
			   NULL,			// Optionally, address of a SOCKADDR_IN struct
			   NULL);			// Optionally, address of variable containing
							// sizeof ( struct SOCKADDR_IN )



	if (theClient == INVALID_SOCKET | theClient==SOCKET_ERROR)
	{
		nret = WSAGetLastError();
		ReportError(nret, "accept()");
        WSACleanup();
        MessageBox(NULL, "error accepting listened on socket", "Socket Indication", MB_OK);
        return NETWORK_ERROR;
	} 
	else
	{
        MessageBox(NULL, "Connection successfully accepted", "Socket Indication", MB_OK);
        }
                break;
				case FD_CONNECT:
                     {
					MessageBox(NULL, "Connection made successfully", "Socket Indication", MB_OK);
					break;
                    }
    }
}

i got it to where when client connects it sends out FD_CONNECT message code "connection successfully accepted". But i have to block out the macro error lparam. However every time i send() from client the server returns a recv() error which is a start cause before it wouldn't even say the connection was accepted on client socket. That means its setting the all the flags now. i changed the position of the functions and put WSAAsyncSelect right after create window.

so the WSAAsyncSelect() is working. I just gotta figure out why everytime i send data on client side...server pops up a error() message saying recv()didn't receive any of the data that was sent. Also i need to be able to call send() on client side from any function without getting errors...not just the function that contained winsocks initialization code.

I'm thinking the reason FD_READ is popping up message on server side saying "recv() returned nothing" has to do with the errors that i was receiving before i commented the error macro lparam out. But i have no idea what to do to fix it....any suggestions anyone?
Last edited on
Is recv() a blocking function....as in it waits until data is received before returning?

Yes, it is a blocking function. You can set a timeout for it using the setsockopt function and the SO_RCVTIMEO parameter.

http://msdn.microsoft.com/en-us/library/ms740476(v=vs.85).aspx

edit: maybe im using the recv function wrong on server side. Say you make a buffer string. when you call receive with buffer string as the second parameter does that mean that receive automatically stores the received data in the buffer

Yes.

1
2
3
4
5
6
7
8
9
10
char buf[5];

//s is a SOCKET that has been created using the socket function
//and is ready to listen (either it has already called listen()/accept()
//on the server side or has called connect() on the client side)

int iResult = recv(s, buf, 5, 0);

//Here, buf will store iResult bytes received if iResult is greater
//than zero. Note that iResult may be less than 5 


on client side to i have to continuosly connect to server before sending and receiving data or do i just connect once then call send() whenever i want to send data?

If the server does not call closesocket on the accept()ed connection, then the client only needs to call connect() once. If the server does call closesocket, then the client needs to re-establish a connection with connect() as the socket has been invalidated.

As for your issues with non-blocking sockets, I haven't had any experiences with it besides the tutorials (which are incomplete). I thought at first, after a call to WSAAsyncSelect, Windows notifies the Window you passed in of each network event that occurs. I thought that, for instance, if you receive a FD_CONNECT event, then you should call accept in the event handler, if you receive a FD_READ event, then you should call recv in the event handler, etc. This may not be the case since I haven't found a complete tutorial on the subject yet.

Another plausible use (again I'm not sure of this), is you call WSAAsyncSelect. Then later, for instance call recv and your program continues in non blocking fashion. When the data is ready from that recv call, FD_READ is sent to your handler.

Again, I'm unsure as to how WSAAsyncSelect actually works (1. Do you call WSAAsyncSelect and then Windows just notifies your Window of incoming events? Or, 2. Do you call WSAAsyncSelect to set up a non-blocking socket, then you proceed as normal calling recv, listen, accept as normal except for the fact that they're now non blocking, with their respective events getting sent to your handler when the non-blocking calls are ready to actually be executed?) So, I won't be able to help you with asynchronous sockets until I actually figure out their guts. Is there anybody else with experience in this regard who can help?
Last edited on
server side gets flagged on FD_READ and does the code (below) but doesn't receive any of the data it was flagged to recv().

You're calling strlen on an uninitialized buffer.

This:

1
2
3
char buffer[2];
//Incoming data; get ready to receive
nret = recv(theClient,buffer, strlen(buffer), 0);

should be:

1
2
3
char buffer[2];
//Incoming data; get ready to receive
nret = recv(theClient, buffer, 2, 0);
I think i got it. Its now receiving the data on server side that i am sending from client. I Was calling WSAAsyncSelect() for each socket on server side not realizing each call to WSAAsyncSelect cancels out the last call to it. So once i realized that i added in a message box in the FD_READ message flag in the callback procedure that popped up message saying "data has been successfully received" if bytesreceived > 0. if not that it would pop up message saying "Recv() returned nothing...error"

edit....but i still need to be able to call send function on client side from any function....not just the
function that i initiated winsock in. That is why i cannot have sending event based. Im guessing i could put each winsock function in a "SetupWinsock(bool, bool, string, string, int, int..ect)" function then have each individual function in an if statement. Then use the bool parameters passed to it to access each if statement. Like "Setupwinsock(Bool send=true,...ect)" and then in the function it would be "if (send) { //send code.... bool send=false,}" since the boolean send parameter was passed as being true it will acess the send function then set the boolean send to false to prevent the send function from being called again next time another function calls "SetupWinsock()".

in a similar manner the boolean statements will be used to call other winsock functions only once...within the function. Also for loops could be used and while loops when sending large amounts of data. also in this manner you could toggle connection to winsock or change winsock settings by calling "SetupWinsock()" and either passing parameters to it or accessing global variables from within the function that specify whether or not you want to be connected to a host...or which host you want to connect to.

isnt udp faster?...but less reliable. I'm guessing its only seeming like the data is being sent slow because it pops up a message everytime data is sent or received. Without the message boxes im sure i could have 20 players sending and receiving coordinates of other players without lag.
Last edited on
You should be able to pass around a SOCKET and call send from a function different than the one it was created in. Maybe you can encapsulate the SOCKET functionality within a class.
and im guessing that you could send virtually any type of data or variable over winsock not just a char buffer[]. am i correct? but the more complex my code gets the more complex i have to check what data is being sent or what command is being sent.
Yes you can send any type of data over a socket (a char buffer is just a bunch of bytes). However, if you're going to send an object, you have to serialize it into a bunch of bytes and the other end has to be able to de-serialize it correctly. If the object instance has a bunch of member variables that are other objects, then the other end has to de-serialize those correctly as well. This means the other end has to have the .h files associated with those objects as well as at least a library for their implementations. Things can go very wrong in this case if the client and server aren't running with compatible run time libraries, for example, among other things. As such, usually only plain old data (POD) is sent across networks to avoid headaches.
Pages: 12