gpt4 book ai didi

C++ SFML 网络 : Can't Establish a TCP Connection

转载 作者:行者123 更新时间:2023-11-28 05:21:32 24 4
gpt4 key购买 nike

第二次更新:ok, here's the wireshark results for what happens when I try to connect to a friend with this program, and it fails. I've tried to remove his info, that's all the redacted lines.

更新:这适用于我本地网络上的所有计算机,使用本地 IP 地址。现在,当我尝试使用公共(public) IP 地址连接到远程计算机时出现问题。大约 20 秒后,客户端收到“无法连接”,然后是“错误编号 3”,其中 3 是 sfml 提供的错误代码。

我只想知道如何建立远程连接。我查看了其他几个似乎与我的相同的示例,并且它们有效。

编辑:我将端口 5000 转发到我的路由器上的计算机,并将该端口连同我的公共(public) IP 地址一起提供给客户端,以防万一。这是我设置的规则的屏幕截图 http://i.imgur.com/Q8Kyu1E.png .我还尝试完全禁用 Windows 防火墙,结果相同。

以下是代码的相关部分:

#include <SFML/System.hpp>
#include <SFML/Network.hpp>
#include <SDL.h>
#include <SDL_image.h>
#include <SDL_ttf.h>
#include <vector>
#include <string>
#include "font.h"
#include "overhead.h"
#include "texture.h"
#include <iostream>

void render(Overhead &overhead, SDL_Rect *clip, Texture &texture, double angle, SDL_Point *centre, SDL_RendererFlip flip) {
SDL_Rect render = { texture.textData.x, texture.textData.y, texture.textData.w, texture.textData.h };
SDL_RenderCopyEx(overhead.renderer, texture.texture, clip, &render, angle, centre, flip);
}

void close(Overhead &overhead, Font &font) {
TTF_CloseFont(font.font);
font.font = NULL;
overhead.closeOverhead();
}

int main(int argc, char* args[]) {
sf::Packet packet;
sf::TcpSocket peer;
sf::TcpListener listener;
unsigned short port;
std::string ip;
sf::IpAddress ipaddress;
char host;
std::cout << "host (y/n): ";
std::cin >> host;
if (host == 'y') {
std::cout << "port number to listen on: ";
std::cin >> port;
std::cout << "IP Address for local connection: " << sf::IpAddress::getLocalAddress() << std::endl;
std::cout << "IP Address for remote connection: " << sf::IpAddress::getPublicAddress() << std::endl;
if (listener.listen(port) != sf::Socket::Done)
std::cout << "listener error" << std::endl;
if (listener.accept(peer) == sf::Socket::Done)
std::cout << "connection successful" << peer.getRemoteAddress() << std::endl;
}
else {
std::cout << "port number to connect to: ";
std::cin >> port;
std::cout << "you chose port number " << port << std::endl;
std::cout << "ip address to connect to: ";
std::cin >> ip;
ipaddress = ip;
sf::Socket::Status status = peer.connect(ipaddress, port);
if (status != sf::Socket::Done) {
std::cout << "cannot connect" << std::endl;
std::cout << "error number: " << status;
}
else if (status == sf::Socket::Done)
std::cout << "connection successful" << std::endl;
}
//other stuff
peer.disconnect();
close(overhead, font);
return 0;
}

最佳答案

我在尝试在本地网络上托管服务器时遇到了完全相同的问题。看来,就像我的一样,您的路由器不允许 NAT Loopback,即通过本地网络访问您的外部 IP(有关 NAT Loopback 的更多详细信息,请参阅 this link)。
事实上,您将能够使用您的公共(public) IP 地址从本地网络外部的客户端访问主机,但如果您想从本地网络内部访问它,则必须使用您的本地地址。

关于C++ SFML 网络 : Can't Establish a TCP Connection,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41402676/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com