1
\$\begingroup\$
#pragma comment(lib, "sfml-network.lib")

#include <iostream>
#include <SFML/Network.hpp>

const unsigned short PORT = 5000;
const std::string IPADDRESS("192.168.0.100");//change to suit your needs

std::string msgSend;

sf::TcpSocket socket;
sf::Mutex globalMutex;
bool quit = false;

void DoStuff(void)
{
    static std::string oldMsg;
    while(!quit)
    {
        sf::Packet packetSend;
        globalMutex.lock();
        packetSend << msgSend;
        globalMutex.unlock();

        socket.send(packetSend);

        std::string msg;
        sf::Packet packetReceive;

        socket.receive(packetReceive);      
        if(packetReceive >> msg)
        {
            if(oldMsg != msg)
                if(!msg.empty())
                {
                    std::cout << msg << std::endl;
                    oldMsg = msg;
                }
        }
    }
}
void Server(void)
{
    sf::TcpListener listener;
    listener.listen(PORT);
    listener.accept(socket);
    std::cout << "New client connected: " << socket.getRemoteAddress() << std::endl;
}
bool Client(void)
{
    if(socket.connect(IPADDRESS, PORT) == sf::Socket::Done)
    {
        std::cout << "Connected\n";
        return true;
    }
    return false;
}
void GetInput(void)
{
    std::string s;
    std::cout << "\nEnter \"exit\" to quit or message to send: ";
    std::cin >> s;
    if(s == "exit")
        quit = true;
    globalMutex.lock();
    msgSend = s;
    globalMutex.unlock();
}
int main(int argc, char* argv[])
{
    sf::Thread* thread = 0;

    char who;
    std::cout << "Do you want to be a server (s) or a client (c) ? ";
    std::cin  >> who;

    if(who == 's')
        Server();
    else
        Client();

    thread = new sf::Thread(&DoStuff);
    thread->launch();

    while(!quit)
    {
        GetInput();
    }
    if(thread)
    {
        thread->wait();
        delete thread;
    }
    return 0;
}
\$\endgroup\$
  • \$\begingroup\$ Just an unrelated comment, you've prompted for s or c for server/client. But you only test for s so anything else will result in client. \$\endgroup\$ – Sam Feb 19 '16 at 20:48
  • 1
    \$\begingroup\$ Welcome to Code Review! Your post looks a little thin and could use more context. I recommend you read this guide for writing a good question. \$\endgroup\$ – SirPython Feb 19 '16 at 20:56
  • \$\begingroup\$ @SirPython checking out the guide now. thanks for the info. \$\endgroup\$ – Jason D Feb 19 '16 at 21:16

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.