Hello everyone
i have a problem with my server, it receives garbage instead of a string.
i look into someone eles code and found that he added this line of code that fix this problem but i dont know how or why it fixes this problem.
can someone please explain this line of code
That doesn't make any sense whatsoever, and if that "fixes" it the code might have more problems. Sounds like perhaps you're trying to receive data from the listen socket later while you should receive on the accept socket.
That doesn't make any sense whatsoever, and if that "fixes" it the code might have more problems. Sounds like perhaps you're trying to receive data from the listen socket later while you should receive on the accept socket.
here is the full code:-
server.h #pragma once
#include <winsock2.h>
#include <stdio.h>
#include <iostream>
iResult = WSAStartup(MAKEWORD(2, 2), &wsaData);
if (iResult != NO_ERROR)
{
wprintf(L"WSAStartup failed with error: %ld\n", iResult);
}
//----------------------
// Create a SOCKET for listening for
// incoming connection requests.
ListenSocket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
if (ListenSocket == INVALID_SOCKET)
{
wprintf(L"socket failed with error: %ld\n", WSAGetLastError());
WSACleanup();
}
}
Server::~Server(void)
{
WSACleanup();
}
void Server::Bind()
{
//----------------------
// The sockaddr_in structure specifies the address family,
// IP address, and port for the socket that is being bound.
Replace ListenSocket with AcceptSocket in recv() instead, and remove that line again as it won't be needed anymore. The listen socket only accepts connections, and then you receive data on the accepted socket.
Replace ListenSocket with AcceptSocket in recv() instead, and remove that line again as it won't be needed anymore. The listen socket only accepts connections, and then you receive data on the accepted socket.
thanks that actually work . the only problem left is when the client type a message for example "How are you doing today sir?" it only prints "How" in the server side, which is weird.
Probably not that weird. How does your client work?
There are many things to think about when sending things over the network.
If you send "1234", the server could get first "1", then "234" separately.
If you send "123" and then "456", the server could get "12345" at once, and then "6".
You need to treat incoming data as a stream and display it as it comes. As of now, you only do one recv() on the server and then display that and exit. Do recv() in a loop until the client disconnects instead.
Another possible problem is that the client input handling cuts the string at a space, so you only send "How", and if you ran the same code again the next time would send "are".