16
Network / Remove Output Messages?
« on: January 17, 2009, 04:28:36 pm »
Ah. Good to know this. Never saw it before...
This section allows you to view all posts made by this member. Note that you can only see posts made in areas you currently have access to.
#include <iostream>
#include <vector>
#include <string>
#include <SFML/System.hpp>
#include <SFML/Network.hpp>
using namespace sf;
using namespace std;
struct connection
{
sf::SocketTCP socket;
sf::Clock timeout;
sf::IPAddress ip;
sf::Packet data;
bool operator==(const connection& other) const;
};
class ConnectionManager
{
private:
sf::Selector<sf::SocketTCP> sockets;
std::vector<connection> connections;
sf::SocketTCP listener;
public:
ConnectionManager();
~ConnectionManager();
void run();
};
bool connection::operator==(const connection& other) const
{
return (socket == other.socket && ip == other.ip);
}
ConnectionManager::ConnectionManager()
{
listener.Listen(4223);
listener.SetBlocking(false);
sockets.Add(listener);
}
ConnectionManager::~ConnectionManager()
{
for(int i = 0; i < connections.size(); i++)
if(connections[i].socket.IsValid()) connections[i].socket.Close();
listener.Close();
}
void ConnectionManager::run()
{
while(1)
{
for(vector<connection>::iterator i = connections.begin(); i < connections.end(); i++)
{
if(!(*i).socket.IsValid())
{
i = connections.erase(i); i--;
}
if((*i).timeout.GetElapsedTime() > 1.5)
{
i->socket.Close();
i = connections.erase(i); i--;
}
}
unsigned int ready = sockets.Wait(0.005f);
for(unsigned int i = 0; i < ready; i++)
{
SocketTCP sock = sockets.GetSocketReady(i);
if(sock == listener)
{
SocketTCP newcon;
IPAddress ip;
if(listener.Accept(newcon,&ip) == Socket::Done)
{
sockets.Add(newcon);
connection c;
c.socket = newcon;
c.socket.SetBlocking(false);
c.ip = ip;
c.timeout = Clock();
connections.push_back(c);
}
}
}
for(vector<connection>::iterator i = connections.begin(); i < connections.end(); i++)
{
if(i->socket.IsValid())
{
Socket::Status state;
state = i->socket.Receive(i->data);
if(state == Socket::Done &&
i->data.GetDataSize() == 4)
{
cout << "packet received successfull" << endl;
//handle packet (omitted)
}
if(state == Socket::NotReady) continue;
}
}
}
}
int main()
{
ConnectionManager c;
c.run();
return 0;
}
SocketTCP ssock;
if(ssock.Connect(4223,"127.0.0.1",1.f))
{
Packet p;
p << (Uint32)0x80A1DA12;
ssock.Send(p);
ssock.Close();
}
return 0;
SocketTCP ssock;
if(ssock.Connect(4223,"127.0.0.1",1.f))
{
Packet p;
p << (Uint32)0x80A1DA12;
ssock.Send(p);
p.Clear();
ssock.Receive(p);
cout << p.GetDataSize() << endl;
ssock.Close();
}
return 0;