我正在使用套接字和UDP编写网络通信应用程序。到目前为止,我能够在同一台机器上运行客户端和服务器,但是现在我想转移到两个独立的机器上。使用的大多数通信代码都基于SFML库提供的示例,但我无法在计算机之间进行连接。每当我尝试通过提供IP和端口来连接计算机时,根本没有来自服务器的响应。这是我的服务器代码:
std::shared_ptr<sf::UdpSocket> startUdpServer()
{
std::cout << "Local address: ";
std::cout << sf::IpAddress::getLocalAddress().toString() << std::endl;
std::cout << "Public address: ";
std::cout << sf::IpAddress::getPublicAddress().toString() << std::endl;
// Create a socket to receive a message from anyone
std::shared_ptr<sf::UdpSocket> socket(new sf::UdpSocket());
// Listen to messages on the first free port
if(socket->bind(sf::Socket::AnyPort) != sf::Socket::Done)
return nullptr;
std::cout << "Server is listening to port " << socket->getLocalPort() << ", waiting for a message... " << std::endl;
return socket;
}
std::pair<sf::IpAddress, unsigned short> runUdpServer(std::shared_ptr<sf::UdpSocket> socket)
{
// Wait for a message
char in[128];
std::size_t received;
sf::IpAddress sender;
unsigned short senderPort;
if (socket->receive(in, sizeof(in), received, sender, senderPort) != sf::Socket::Done)
{
std::cout << "Connection error" << std::endl;
return std::make_pair(sender, senderPort);
}
std::cout << "Message received from client " << sender << ": \"" << in << "\"" << std::endl;
return std::make_pair(sender, senderPort);
}
void sendUdpMessage(std::shared_ptr<sf::UdpSocket> socket, std::pair<sf::IpAddress, unsigned short> config,
std::string message)
{
// Send an answer to the client
const char* out = message.c_str();
if (socket->send(out, sizeof(char) * message.length(), config.first, config.second) != sf::Socket::Done)
return;
std::cout << "Message sent to the client: \"" << out << "\"" << std::endl;
}
和客户:
std::shared_ptr<sf::UdpSocket> startUdpClient()
{
// Ask for the server address
sf::IpAddress server;
do
{
std::cout << "Type the address or name of the server to connect to: ";
std::cin >> server;
}
while (server == sf::IpAddress::None);
unsigned short port;
std::cout << "Type the port number: ";
std::cin >> port;
// Create a socket for communicating with the server
std::shared_ptr<sf::UdpSocket> socket(new sf::UdpSocket());
sf::Packet packet;
// Send a message to the server
const char out[] = "Hi, I'm a client";
if (socket->send(out, sizeof(out), server, port) != sf::Socket::Done)
return nullptr;
std::cout << "Message sent to the server: \"" << out << "\"" << std::endl;
return socket;
}
void runUdpClient(std::shared_ptr<sf::UdpSocket> socket, Buffer<std::string>& value)
{
// Receive an answer from anyone (but most likely from the server)
char in[256];
std::size_t received;
sf::IpAddress sender;
unsigned short senderPort;
if (socket->receive(in, sizeof(in), received, sender, senderPort) != sf::Socket::Done)
return;
value.emplace_back(in);
}
我能做些什么才能让它发挥作用?有什么想法吗?
编辑#1:
正如所指出的,我忘了提到我正在使用的系统。目前两者都是Windows,但我打算以不同的组合使用所有系统(据我所知,套接字与操作系统的通信无关)。