我创建了一个基于套接字的SFML C ++程序,包括客户端和服务器。 问题是当我从客户端向服务器发送x和y坐标时,结果是意外的。服务器显示更改x和y坐标但它们不正确。请帮忙。
服务器代码:
#include <SFML\Network.hpp>
#include <SFML\Window.hpp>
#include <iostream>
#include <cstdlib>
using namespace std;
using namespace sf;
int main()
{
float x = 0.0, y = 0.0;
Packet packet;
TcpListener listener;
TcpSocket socket;
listener.listen(26200);
listener.accept(socket);
cout<<"Connected to client!";
socket.setBlocking(false);
while(true)
{
if(Keyboard::isKeyPressed(Keyboard::Key::Escape)) break;
if(socket.receive(packet) != Socket::Status::Done) continue;
cout<<endl<<"Recieved packet";
if( packet >> x >> y )
{
cout<<"\nX: "<<x<<" Y: "<<y;
packet.clear();
}
packet.clear();
system("cls");
}
system("pause");
return 0;
}
客户代码:
#include <SFML\Window.hpp>
#include <SFML\Graphics.hpp>
#include <SFML\Network.hpp>
#include <iostream>
using namespace std;
using namespace sf;
int main()
{
IpAddress ip = IpAddress::getLocalAddress();
TcpSocket socket;
Packet packet;
Vector2f prevpos;
socket.connect(ip,26200);
cout<<"Connected to server!";
CircleShape ball;
ball.setPosition(400,300);
ball.setRadius(10.0f);
ball.setFillColor(Color::Blue);
ball.setOrigin(2.0f,2.0f);
sf::RenderWindow window(sf::VideoMode(800, 600), "SFML works!");
while(true)
{
window.clear(Color::Black);
prevpos = ball.getPosition();
if(Keyboard::isKeyPressed(Keyboard::Key::Escape)) break;
if(Keyboard::isKeyPressed(Keyboard::Key::Up)) ball.move(0.0,-1.0);
if(Keyboard::isKeyPressed(Keyboard::Key::Down)) ball.move(0.0,1.0);
if(Keyboard::isKeyPressed(Keyboard::Key::Left)) ball.move(-1.0,0.0);
if(Keyboard::isKeyPressed(Keyboard::Key::Right)) ball.move(1.0,0.0);
window.draw(ball);
window.display();
if(prevpos != ball.getPosition())
{
packet << ball.getPosition().x << ball.getPosition().y ;
socket.send(packet);
packet.clear();
}
packet.clear();
}
return 0;
}