i've started doing a project with networking. But after setting up a the std::thread, the while(true)-loop wont start.
The first thing i have done is setting up the std::thread which is listening for new clients. In the function which the thread is using is a while(true)-loop, which perfectly works. In in the main thread after initializing the serverListener std::thread, is again a while(true)-loop which tries to recieve data, but this loop wont start, except when I put a std::cout in the while-loop before the for-loop, but this spams my console.
Variables and inclusions:
#include <SFML/Network.hpp>
#include <iostream>
#include <list>
#include <thread>
#define PORT 1337
unsigned int clientCounter = 0;
sf::TcpSocket clients[5];
sf::Packet packet;
The function which the std::thread is using:
void serverListener() {
sf::TcpListener listener;
listener.listen(PORT);
while (true) {
if (listener.accept(clients[clientCounter]) == sf::Socket::Status::Done) {
std::cout << "New client connected: "
<< clients[clientCounter].getRemoteAddress() << std::endl;
clientCounter++;
}
}
}
Main thread:
int main()
{
std::thread serverListenerThread(&serverListener);
while(true) {
//std::cout << "Some message"; <----- when uncomment, the loop works?
for (int i = 0; i < clientCounter; i++) {
std::string message = "";
packet >> message;
if (clients[i].receive(packet) == sf::Socket::Status::Done) {
message += std::to_string(i);
std::cout << message << std::endl;
}
}
}
return 0;
}
==to a!=if (listener.accept(clients[clientCounter]) != sf::Socket::Status::Done) {as shown in the tcp example here - sfml-dev.org/tutorials/2.5/network-socket.php - estabroolistenoracceptcalls return the expected status codes> - BotjeclientCounterin one thread will be seen in another. Change its type tostd::atomic<unsigned int>. - Pete Becker