Welcome, Guest. Please login or register. Did you miss your activation email?

Show Posts

This section allows you to view all posts made by this member. Note that you can only see posts made in areas you currently have access to.


Topics - Shinoken

Pages: [1]
1
Network / Code using udp socket not working
« on: November 07, 2022, 05:06:40 pm »
Why does this code work if i test it by opening the .exe file 2 times on my computer but doesn't if i try it on separate ones?

#include "SFML\Graphics.hpp"
#include "SFML\Window.hpp"
#include "SFML\Network.hpp"\

#include <iostream>
#include <vector>

using namespace std;

int main()
{
        sf::UdpSocket socket;
        sf::IpAddress thisIp = sf::IpAddress::getLocalAddress();
        socket.bind(sf::Socket::AnyPort);
        char clientServerOption;
        cout << "Type 'c' for client and 's' for server"<<endl;
        cin >> clientServerOption;

        if(clientServerOption == 'c')
        {
                string str;
                cout << "Type the IP address here" << endl;
                cin >> str;
                sf::IpAddress serverIp = sf::IpAddress(str);
                cout << "Type the Server Port here" << endl;
                cin >> str;
                unsigned short serverPort = stoi(str);

                cout << "Send: ";
                cin.ignore();
                getline(cin, str, '\n');

                sf::Packet packet;
                packet << str;
                socket.send(packet, serverIp, serverPort);
                socket.receive(packet, serverIp, serverPort);
                packet >> str;
                cout << "Server says: " << str << endl;
        }
        else if(clientServerOption == 's')
        {
                vector <sf::IpAddress> clientIps;
                vector <unsigned short> clientPorts;
                clientIps.push_back(sf::IpAddress());
                clientPorts.push_back(0);
                unsigned short thisPort = socket.getLocalPort();
                cout << "Server hosted with ip " << thisIp << " on port " << thisPort << endl;
                sf::Packet packet;
                socket.receive(packet, clientIps.at(0), clientPorts.at(0));
                string getMessage;
                packet >> getMessage;
                packet.clear();
                cout << getMessage << endl;
                packet << "Message Received";
                socket.send(packet, clientIps.at(0), clientPorts.at(0));
        }

        system("pause");
       
}

Pages: [1]
anything