Hello
I have a working server at last:
////////////////////////////////////////////////////////////
// Headers
////////////////////////////////////////////////////////////
#include <SFML/Network.hpp>
#include <SFML/System.hpp>
#include <iostream>
sf::SelectorTCP Selector;
sf::IPAddress Address;
sf::SocketTCP Listener;
sf::SocketTCP Socket;
unsigned int NbSockets;
void Listen(void*){
Selector.Add(Listener);
while (true){
NbSockets = Selector.Wait();
for (unsigned int i = 0; i < NbSockets; ++i)
{
// Get the current socket
Socket = Selector.GetSocketReady(i);;
if (Socket == Listener)
{
// If the listening socket is ready, it means that we can accept a new connection
sf::SocketTCP Client;
Listener.Accept(Client, &Address);
std::cout << "Client connected ! (" << Address << ")" << std::endl;
// Add it to the selector
Selector.Add(Client);
}else{
// Else, it is a client socket so we can read the data he sent
char Message[128]; //128
std::size_t Received;
Socket = Selector.GetSocketReady(0);;
if (Socket.Receive(Message, sizeof(Message), Received) == sf::Socket::Done){
// Show the message
std::cout << "Message received from the client : \"" << Message << "\"" << std::endl;
}
}
}
}
}
void Send(void*){
char ToSend[128];
for(;;){
std::cin>>ToSend;
if (Socket.Send(ToSend, sizeof(ToSend)) != sf::Socket::Done)
{
std::cout << "Message sent to the client : \"" << ToSend << "\"" << "to" << &Socket << std::endl;
}
}
}
// Choose a random port for opening sockets (ports < 1024 are reserved)
int main()
{
if (!Listener.Listen(4567)){
// Error...
}
sf::Thread Thread1(&Listen);
sf::Thread Thread2(&Send);
Thread1.Launch();
Thread2.Launch();
return 0;
}
I do however have two problems.
1) How can i select which client to send the string to?
2)How can i allow a client to reconnect after it has disconnected?
Thanks in advance.
TobiasSmollett