c++ - 使用套接字 SFML 时窗口没有响应

标签 c++ sockets networking udp sfml

我正在做一些简单的 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);
}

最佳答案

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

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

Relevent docs here

关于c++ - 使用套接字 SFML 时窗口没有响应,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43417431/

相关文章:

c++ - Qt 如何在幕后共享 OpenGL 上下文?

linux - 如何将多个接口(interface)绑定(bind)到原始套接字

java - 服务器端点调用地址和重定向地址返回不同的IP地址

java - 使用 java 套接字类获取网页

Azure SNAT 耗尽 - 我如何知道它何时发生?

C++,将结构特征作为参数传递给函数

c++ - 定时器上的Arduino PID

c++ - 将当前模板用作模板参数之一的模板参数

c - 在同一UDP数据包中发送ASCII字符和int

perl - Perl客户端/服务器套接字