使用套接字SFML时窗口没响应

时间:2017-04-14 18:48:10

标签: 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);
}

1 个答案:

答案 0 :(得分:2)

没有任何参数的

sf::milliseconds(5)将永远等待,直到其中一个套接字收到某些内容,因此您无法响应窗口中的事件。

如果您等待一段时间,例如// Disable TOC button window.HelpViewer.showTOCButton(false); // Enable TOC button // If you call this on window load it will flash active for a brief second // and then disable again. Call if after a delay of 250ms and is works fine // Not sure what the second variable does yet, but passing false works fine window.HelpViewer.showTOCButton( true, false, function() { //do something to toggle TOC in your webpage }); // Apple stores the status of the TOC using a window session variable, // you can use this to keep the TOC open or closed when transitioning // between pages. window.sessionStorage.getItem("toc"); ,那么您可以继续轮询事件

Relevent docs here