I am new to C++ and SFML. So I am playing with TCP recently and found out that the code I wrote only works in Local Host but not internet.
At first I thought there is something wrong in my code but after testing the TCP Example code from the documentation, it still seems like only works in local host.
It will be nice if someone can point out what I did wrong or test it out too.
Below is the slightly modified code from the official documentation:
https://www.sfml-dev.org/documentation/2.4.2/classsf_1_1TcpSocket.php#include <iostream>
#include<SFML/Network.hpp>
int main()
{
std::cout << "Client[c] or server[s]? " << std::endl;
std::string consoleInput;
std::getline(std::cin, consoleInput);
if(consoleInput == "c")
{
std::cout << "Input server address: " << std::endl;
std::getline(std::cin, consoleInput);
// ----- The client -----
// Create a socket and connect it to port 55001
sf::TcpSocket socket;
socket.connect(consoleInput, 55001);
// Send a message to the connected host
std::string message = "Hi, I am a client";
socket.send(message.c_str(), message.size() + 1);
// Receive an answer from the server
char buffer[1024];
std::size_t received = 0;
socket.receive(buffer, sizeof(buffer), received);
std::cout << "The server said: " << buffer << std::endl;
std::cout << "Press any key to close" << std::endl;
std::cin >> message;
}
else if(consoleInput == "s")
{
// ----- The server -----
// Create a listener to wait for incoming connections on port 55001
sf::TcpListener listener;
listener.listen(55001);
//Show ip address
std::cout << sf::IpAddress::getLocalAddress() << std::endl;
std::cout << sf::IpAddress::getPublicAddress() << std::endl;
// Wait for a connection
sf::TcpSocket socket;
listener.accept(socket);
std::cout << "New client connected: " << socket.getRemoteAddress() << std::endl;
// Receive a message from the client
char buffer[1024];
std::size_t received = 0;
socket.receive(buffer, sizeof(buffer), received);
std::cout << "The client said: " << buffer << std::endl;
// Send an answer
std::string message = "Welcome, client";
socket.send(message.c_str(), message.size() + 1);
std::cout << "Press any key to close" << std::endl;
std::cin >> message;
}
return 0;
}
When testing this code in local host, it does fine: (Untitled.png)
But when it comes to testing with remote devices: (unknown.png)
One of my friend got gibberish when he connects to me and I can't even connect to him. Note that firewall and anti-virus has been turned off.
Edit:
Obviously when I use this example, there is no status return. But when I use my own code, the server hosts successfully but the status returned on the client side when sending is "Not Ready".
Edit 2:
Got it, its just port forwarding. Didn't know it needs to be done before hosting server.