I've been trying to send data through UDP from the server to the client, but for some reason, it returns a -1 error (10057 error - socket not connected).
How ever, just before I'm sending a packet, I'm also recieving a packet..
SOCKET ClientSocket = ServerOn();
service.sin_family = AF_INET;
service.sin_addr.s_addr = inet_addr("0.0.0.0");
service.sin_port = htons(2583);
char *recvbuff = newchar;
int size = 0;
recv(ClientSocket, recvbuff, strlen(recvbuff), NULL);
std::cout << "New Connection!" << std::endl;
* Some small calculations that takes o(1) time *
* Theres some data stored in std::string data
send(ClientSocket, data.c_str(), data.length(), NULL); // Sending the data
iResult = WSAGetLastError(); // iResult turns 10057
Which means the socket isnt connected.
So, what is my problem in the code?
I used to have another recv function after the line of the send function, so it couldent be that I had lost the connection. 2 recv functions one after one works fine, but the send one allways fails and returns -1... Why is that?
This is the server side BTW.
In a client-server network, the server listens for connections. When using the sockets library, a server must bind to an address/port endpoint. This allows clients to find the server by communicating with that address/port.
So, in your example, you created a UDP server and you've bound to address INADDR_ANY / port 2583. It is not uncommon for a computer to have multiple network interfaces; for example, the loopback adapter, wifi and an ethernet adapter. You server will listen for connections on all these interfaces, and port 2583.
Now, how do you reach it?
Let's assume the wifi interface is active and connected to a home router and was assigned address 192.168.1.3.
Let's assume that the client computer is also connected to the same home router.
Then the client computer ought to be able to ping the computer running your server program. So your should be able to run:
The ping proves that your network is working and the client can reach the server.
Then, run your client. The client must used sendto/recvfrom rather than send/recv. The address is sends to is 192.168.1.3:2583.
It makes no sense for the client to:
1. use send/recv
2. use address 0.0.0.0:2583
You can't write network software without learning a little about networking. After all, if you don't understand it, how can you create instructions for it?