运行 多台计算机上的SFML tcp网络程序

Run SFML tcp Network program on multiple computers

我打算用 SFML 制作一个 TCP 网络 2 人游戏,所以我已经看过这个 Youtube 视频。 -> enter link description here。在那段视频之后,我实际上制作了那个程序,它在我的笔记本电脑上运行良好。但是当我 运行 在多台计算机上执行此操作时,它不会。在那段视频中,他说如果我将 IP address::getLocalAdress 设置为 ipAdress::getPublicAdress,我可以 运行 在另一台计算机上执行此操作。我试过了,但还是一样。 有人会检查我的代码吗??

#include <SFML/Graphics.hpp>
#include <SFML/Audio.hpp>
#include <SFML/Network.hpp>
#include <string>
#include <iostream>
using namespace std;

int main() {
sf::IpAddress ip = sf::IpAddress::getLocalAddress();
sf::TcpSocket socket;
char connectionType;

std::cout << "Enter (s) for sever, Enter (c) for client" << std::endl;
cin >> connectionType;

if (connectionType == 's') { 
    sf::TcpListener listener;
    listener.listen(2000);
    listener.accept(socket);
}
else
    socket.connect(ip, 2000);

sf::RectangleShape rect1, rect2;
rect1.setSize(sf::Vector2f(20, 20));
rect2.setSize(sf::Vector2f(20, 20));

rect1.setFillColor(sf::Color::Red);
rect2.setFillColor(sf::Color::Blue);

sf::RenderWindow app(sf::VideoMode(800,600,32),"SFML_ProjectBase", sf::Style::Resize);
sf::Vector2f prevPosition, p2Position;

socket.setBlocking(false);

bool update = false;

while (app.isOpen()) {
    sf::Event e;
    while (app.pollEvent(e)) {
        if (e.type == sf::Event::Closed || (e.type == sf::Event::KeyReleased && e.key.code == sf::Keyboard::Escape)) {
            app.close();
        }
        else if (e.type == sf::Event::GainedFocus) {
            update = true;
        }
        else if (e.type == sf::Event::LostFocus) {
            update = false;
        }
    }
    prevPosition = rect1.getPosition();

    if (update) {
        if (sf::Keyboard::isKeyPressed(sf::Keyboard::Right)) 
            rect1.move(0.2f, 0.0f);
        if (sf::Keyboard::isKeyPressed(sf::Keyboard::Left)) 
            rect1.move(-0.2f, 0.0f);
        if (sf::Keyboard::isKeyPressed(sf::Keyboard::Up)) 
            rect1.move(0.0f, -0.2);
        if (sf::Keyboard::isKeyPressed(sf::Keyboard::Down)) 
            rect1.move(0.0f, 0.2f);
    }

    sf::Packet packet;

    if (prevPosition != rect1.getPosition()) {
        packet << rect1.getPosition().x << rect1.getPosition().y;
        socket.send(packet);
    }
    socket.receive(packet);
    if (packet >> p2Position.x >> p2Position.y) {
        rect2.setPosition(p2Position);
    }
    app.draw(rect1); 
    app.draw(rect2);

    app.display();
    app.clear();
}
system("pause");
return 0;
}

您的问题只是您在 socket.connect(ip, 2000); 中设置了错误的目标 IP。

  • 如果您正在使用 sf::IpAddress::getLocalAddress(),您将获得程序 运行 所在的当前机器的 IP。

  • 如果您使用 sf::IpAddress::getPublicAddress(),您将获得您的 LAN 暴露给互联网的 IP(通常是您路由器的 WAN IP)。为此,它需要适当的端口转发,但也可能会阻止从 LAN 端连接的客户端(防止本地恶意软件伪造互联网域的安全功能)。

作为解决方案,将 ip 机器的 IP 地址设置为 运行 服务器。然后它应该连接。