Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <SFML/Graphics.hpp>
- #include <SFML/Network.hpp>
- #include <iostream>
- #include <thread>
- #include <mutex>
- const unsigned short port = 5310;
- sf::TcpSocket socket1;
- sf::TcpListener listenertcp;
- sf::Packet sendingpacket;
- sf::Packet receivingpacket;
- std::mutex mutex1;
- bool quit = false;
- void listener()
- {
- listenertcp.listen(port);
- while(!quit)
- {
- if(listenertcp.accept(socket1) == sf::Socket::Done)
- {
- mutex1.lock();
- std::cout << "Client just connected " << socket1.getRemoteAddress() << std::endl; //appilcation might need to tell this client to connect to the remote ip
- mutex1.unlock();
- }
- }
- }
- void receive(sf::Packet* receivepacket)
- {
- std::string outputr;
- while(!quit)
- {
- if(socket1.receive(*receivepacket) == sf::Socket::Done)
- {
- *receivepacket >> outputr;
- mutex1.lock();
- std::cout << outputr << std::endl;
- mutex1.unlock();
- }
- }
- }
- int main()
- {
- std::string input;
- std::cout << "Enter /server or /client" << std::endl;
- std::cin >> input;
- if(input == "/server")
- {
- std::cout << "Server is listening on port " << port << std::endl;
- std::thread listen(listener);
- std::thread messagereceive(receive, &receivingpacket);
- listen.join();
- messagereceive.join();
- }
- else if(input == "/client")
- {
- std::cout << "input /connect to connect to a client." << std::endl;
- std::cout << "input /quit to quit the application." << std::endl;
- std::cout << "input /myip to get your ip address." << std::endl;
- while(!quit)
- {
- std::string userinput;
- std::cin >> userinput;
- if(userinput == "/connect")
- {
- std::string ip;
- std::cout << "Please input the ip address you'd like to connect to" << std::endl;
- std::cin >> ip;
- sf::Socket::Status status = socket1.connect(ip, port);
- if(status != sf::Socket::Done)
- {
- std::cout << "invalid ip address" << std::endl;
- }
- else
- {
- std::cout << "connected to client at " << ip << "address" << std::endl;
- }
- }
- else if(userinput == "/myip")
- {
- sf::IpAddress myip;
- std::string myipstring;
- myip = sf::IpAddress::getPublicAddress();
- myipstring = myip.toString();
- std::cout << myipstring << std::endl;
- }
- else if(userinput == "/quit")
- {
- quit = true;
- }
- else
- {
- sendingpacket << userinput;
- mutex1.lock();
- socket1.send(sendingpacket);
- mutex1.unlock();
- }
- }
- }
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement