第二次更新: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.C++ SFML網絡:無法建立TCP連接
更新:這適用於我的本地網絡上的所有計算機,使用本地IP地址。這是當我嘗試連接到現在有問題的公共IP地址的遠程計算機時。客戶在大約20秒後得到「無法連接」,然後是「錯誤編號3」,其中3是sfml提供的錯誤代碼。
我只想知道如何建立遠程連接。我看過其他幾個與我的看法完全相同的例子,它們都有效。
編輯:我將端口5000轉發到我的路由器上的計算機,並將該端口與我的公共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;
}
你在客戶端輸入什麼ip地址?含義是90.50.90.50還是192.168.1.100? – Rokner
它是90.50.90.50的類型,即。公共IP地址。 我嘗試切換代碼,以使用本地IP地址(使用sf :: IpAddress :: getLocalAddress()),它實際上工作,雖然我不認爲這將是非常有用的連接到人以外的人我的家庭網絡。 – trashviolent
'無法連接'不是有用的信息。它只是一個由您的應用程序打印的文本字符串,用於響應任何大約十幾種可能的失敗情況。您至少需要打印'errno',或者最好是'strerror()'的結果。或者調用'perror()'。在你提供這些信息之前,你的問題是無法回答的。 – EJP