【问题标题】:Window not responding while using sockets SFML使用套接字 SFML 时窗口没有响应
【发布时间】:2017-04-14 18:48:10
【问题描述】:

我正在做一些简单的 SFML 游戏,我想使用 udp 套接字进行网络通信。但问题是,如果我尝试使用套接字接收的坐标更新圆的位置,窗口被阻塞并且没有响应。这是下面的代码。有谁知道问题出在哪里?

#include <SFML/Graphics.hpp>
#include <SFML/Network.hpp>
#include <iostream>
#include <string>
#include <iostream>

int posX=100,posY=220,x=5;
sf::UdpSocket receiver;
sf::SocketSelector selector;

void changePosition ();
void defineWindow(sf::RenderWindow &window);
void drawCircle(sf::CircleShape &circle, sf::RenderWindow &window);

int main ()
{
  receiver.bind(15000);
  selector.add(receiver);

  sf::RenderWindow window (sf::VideoMode(800,600), "Krugovi");

  defineWindow (window);

  return 0;
}

void changePosition ()
{
  if (x>0 && posX+x>685) {
    posX=685;
    x=-x;
  }
  else if (x<0 && posX+x<15) {
    posX=15;
    x=-x;
  }
  else
    posX=posX+x;
}

void defineWindow(sf::RenderWindow &window)
{
  sf::CircleShape circle(50);
  sf::Event event;
  sf::Clock clock;

  while (window.isOpen()) {
    while(window.pollEvent(event)) {
      if (event.type == sf::Event::KeyPressed) {
        if (event.key.code == sf::Keyboard::Escape)
          window.close();
      }
      if (event.type==sf::Event::Closed)
        window.close();
    }

    window.clear(sf::Color::White);

    char msg[5];
    size_t received;
    sf::IpAddress ip;
    unsigned short port;

    std::string string;

    if (selector.wait()) {
       if(receiver.receive(msg,sizeof(msg),received,ip,port)==sf::UdpSocket::Done) {
        posX=atoi(msg);
      }
    }

    drawCircle(circle,window);

    window.display();
  }
}

void drawCircle(sf::CircleShape &circle, sf::RenderWindow &window)
{
  circle.setFillColor(sf::Color::Yellow);
  circle.setOutlineThickness(15);
  circle.setOutlineColor(sf::Color::Red);
  circle.setPosition(posX,posY);
  window.draw(circle);
}

【问题讨论】:

  • 您需要使用正确的标志启用非阻塞套接字。我不熟悉 SFML,但您应该在文档的某个地方找到启用该选项的方法。然后,您将需要修改您的代码以继续运行,而不会在网络上接收到数据。

标签: c++ sockets networking udp sfml


【解决方案1】:

sf::SocketSelector::wait() 没有任何参数将永远等待,直到在它的一个套接字上接收到某些东西,因此您不会响应窗口中的事件。

如果你给它一个等待时间,例如sf::milliseconds(5),那么你可以继续轮询事件

Relevent docs here

【讨论】:

    猜你喜欢
    • 2018-10-16
    • 2021-10-15
    • 1970-01-01
    • 2019-01-28
    • 1970-01-01
    • 1970-01-01
    • 2021-03-19
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多