Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #define _WIN32_WINNT 0x0601
- #include <boost/asio.hpp>
- #include <boost/system/system_error.hpp>
- #include <boost/bind.hpp>
- #include <Windows.h>
- #include <iostream>
- #define MAX_CLIENTS 500
- #define MAX_LEN 16000
- using namespace std;
- boost::asio::io_service io;
- boost::asio::ip::tcp::acceptor *Endpoint;
- struct stClient
- {
- stClient() : socket(io) {}
- unsigned int iID;
- boost::asio::ip::tcp::socket socket;
- bool bConnected;
- char cBuffer[MAX_LEN];
- } g_Clients[MAX_CLIENTS];
- void OnConnected(stClient *Client)
- {
- cout << Client->iID << " hat sich verbunden!" << endl;
- }
- void OnData(stClient *Client,const char *data,size_t size)
- {
- cout << Client->iID << ": " << data << endl;
- }
- void OnDisconnect(stClient *Client)
- {
- cout << Client->iID << " hat die Verbindung getrennt" << endl;
- }
- /* Wenn ein Client Daten gesendet hat */
- void handle_read(stClient *client,const boost::system::error_code& er,const size_t transferred)
- {
- if(er)
- {
- /* Wenn der Client die Verbindung getrennt hat */
- if(client->bConnected)
- OnDisconnect(client);
- client->bConnected = false;
- return;
- }
- /* Daten erfolgreich bekommen */
- OnData(client,client->cBuffer,transferred);
- memset(client->cBuffer,0,MAX_LEN);
- client->socket.async_read_some(boost::asio::buffer(
- client->cBuffer,MAX_LEN),
- boost::bind(handle_read,client,boost::asio::placeholders::error,boost::asio::placeholders::bytes_transferred));
- }
- int GetFreeSlot()
- {
- for(int i=0;i<MAX_CLIENTS;i++)
- if(!g_Clients[i].bConnected)
- return i;
- return -1;
- }
- void handle_accept(stClient *client,const boost::system::error_code& er)
- {
- if(er)
- {
- cout << er.message() << endl;
- return;
- }
- /* Code, wenn sich ein Client verbunden hat */
- OnConnected(client);
- client->socket.async_read_some(boost::asio::buffer(client->cBuffer,MAX_LEN),
- boost::bind(handle_read,client,boost::asio::placeholders::error,boost::asio::placeholders::bytes_transferred));
- client->bConnected = true;
- int slot = GetFreeSlot();
- if(slot == -1)
- return;
- Endpoint->async_accept(g_Clients[slot].socket,boost::bind(handle_accept,&g_Clients[slot],boost::asio::placeholders::error));
- }
- int main()
- {
- for(int i=0;i<MAX_CLIENTS;i++)
- {
- g_Clients[i].bConnected=false;
- g_Clients[i].iID = i;
- }
- int slot = GetFreeSlot();
- if(slot == -1)
- return 0;
- Endpoint = new boost::asio::ip::tcp::acceptor(io,boost::asio::ip::tcp::endpoint(boost::asio::ip::tcp::v4(),1337));
- Endpoint->async_accept(g_Clients[slot].socket,boost::bind(handle_accept,&g_Clients[slot],boost::asio::placeholders::error));
- io.run();
- getchar();
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement