Im new to networking and Im trying to create a simple instant messenger to better understand it.
My code is:
#include <iostream>
#include <string>
#include <sstream>
#include <SFML\System.hpp>
#include <SFML\Network.hpp>
void SendData(void*);
void RecieveData(void*);
int main()
{
sf::Thread RecieveData(&RecieveData);
RecieveData.Launch();
std::cout << "Type the IP address you wish to connect to, then press enter." << std::endl;
std::cout << "Example: 192.168.0.1" << std::endl;
std::string FriendIP;
std::cin >> FriendIP;
sf::Thread SendData(&SendData, &FriendIP);
SendData.Launch();
RecieveData.Wait();
SendData.Wait();
return EXIT_SUCCESS;
}
void SendData(void* UserData)
{
std::string* FriendIP = static_cast<std::string*>(UserData);
sf::SocketTCP Client;
if(Client.Connect(5000, *FriendIP) == sf::Socket::Done) // insert message loop here
{
std::cout << "Message to send:" << std::endl;
std::string Message;
std::getline(std::cin, Message);
sf::Packet Send;
Send << Message;
if(Client.Send(Send) == sf::Socket::Done)
{
std::cout << "Message sent" << std::endl;
}
else
{
std::cout << "Error: Could not send message" << std::endl;
}
}
else
{
std::cout << "Error: Could not connect to " << *FriendIP << std::endl;
}
}
void RecieveData(void* UserData)
{
sf::SocketTCP Listener;
if(!Listener.Listen(5000))
{
std::cout << "Error: Could not listen for connections on port 5000" << std::endl;
}
else
{
sf::IPAddress ClientAddress;
sf::SocketTCP Client;
if(Listener.Accept(Client, &ClientAddress) == sf::Socket::Done)
{
sf::Packet Recieved;
std::string Message;
if(Client.Receive(Recieved) == sf::Socket::Done)
{
if(Recieved >> Message)
{
std::cout << Message << std::endl;
}
else
{
std::cout << "Error: Could not read data from packet" << std::endl;
}
}
else
{
std::cout << "Error: Could not recieve packet" << std::endl;
}
}
else
{
std::cout << "Error: Could not accept connection from " << ClientAddress << std::endl;
}
}
}
Iv tried it several different ways and have become stuck. I always get the same error, where my socket wont connect. Iv tried it with both my IP address (local and public) as well as with my friend who was also running this program on his computer.
Any thoughts or suggestions, Im fairly new at programming so anything would help. Thanks