0
我正在做一些簡單的SFML遊戲,並且我想使用udp套接字進行網絡通信。但問題是,如果我嘗試使用套接字接收的座標更新圓圈的位置,則該窗口被阻塞並且不響應。這是下面的代碼。有誰知道問題是什麼?使用套接字時窗口沒有響應SFML
#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並不熟悉,但在文檔的某處您應該找到啓用該選項的方式。然後,您需要修改代碼,以便在網絡上沒有收到數據的情況下繼續運行。 – rlam12