[英]Random output when receiving data from SFML socket
When running this code I am receiving completely random output when entering 'C' and nothing happening when entering 'S'. 当运行此代码时,我在输入“C”时接收到完全随机的输出,并且在输入“S”时没有发生任何事情。
Any help is greatly appreciated! 任何帮助是极大的赞赏!
#include <iostream>
#include <string>
#include <SFML/Network.hpp>
int main()
{
sf::IpAddress ip = sf::IpAddress::getLocalAddress();
sf::TcpSocket socket;
char connectionType, buffer[2000];
std::size_t received;
std::cout << "C for client, S for server" << std::endl;
std::cin >> connectionType;
std::string packetText = "test";
if (connectionType == 'S')
{
sf::TcpListener listener;
listener.listen(2000);
listener.accept(socket);
}
else if (connectionType == 'C')
{
socket.connect(ip, 2000);
}
socket.send(packetText.c_str(), packetText.length() + 1);
socket.receive(buffer, sizeof(buffer), received);
std::cout << buffer << std::endl;
system("pause");
}
You might want to handle that as an error. 您可能希望将其作为错误处理。 What is going on is the connect()
, send()
, and receive()
are all failing but you aren't checking the return values. 发生了什么是connect()
, send()
和receive()
都失败但你没有检查返回值。 Additionally, you might want to zero out received
and check that you actually received something before printing using the buffer. 此外,您可能希望将received
清零,并在使用缓冲区打印之前检查您是否确实收到了某些内容。 – Sean Cline - 肖恩克莱恩
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.