Exemple #1
0
void HttpHandler::HandleRequest(const HttpRequest* req, HttpResponse* resp) {
    switch (req->Method()) {
    case HttpRequest::METHOD_HEAD:
        HandleHead(req, resp);
        break;
    case HttpRequest::METHOD_GET:
        HandleGet(req, resp);
        break;
    case HttpRequest::METHOD_POST:
        HandlePost(req, resp);
        break;
    case HttpRequest::METHOD_PUT:
        HandlePut(req, resp);
        break;
    case HttpRequest::METHOD_DELETE:
        HandleDelete(req, resp);
        break;
    case HttpRequest::METHOD_OPTIONS:
        HandleOptions(req, resp);
        break;
    case HttpRequest::METHOD_TRACE:
        HandleTrace(req, resp);
        break;
    case HttpRequest::METHOD_CONNECT:
        HandleConnect(req, resp);
        break;
    default:
        MethodNotAllowed(req, resp);
        break;
    }
}
Exemple #2
0
void CTcpAgent::HandleIo(CONNID dwConnID, TSocketObj* pSocketObj, TBufferObj* pBufferObj, DWORD dwBytes, DWORD dwErrorCode)
{
	ASSERT(pBufferObj != nullptr);
	ASSERT(pSocketObj != nullptr);

	if(dwErrorCode != NO_ERROR)
	{
		HandleError(dwConnID, pBufferObj, dwErrorCode);
		return;
	}

	if(dwBytes == 0 && pBufferObj->operation != SO_CONNECT)
	{
		AddFreeSocketObj(dwConnID, SCF_CLOSE);
		AddFreeBufferObj(pBufferObj);
		return;
	}

	pBufferObj->buff.len = dwBytes;

	switch(pBufferObj->operation)
	{
	case SO_CONNECT:
		HandleConnect(dwConnID, pSocketObj, pBufferObj);
		break;
	case SO_SEND:
		HandleSend(dwConnID, pSocketObj, pBufferObj);
		break;
	case SO_RECEIVE:
		HandleReceive(dwConnID, pSocketObj, pBufferObj);
		break;
	default:
		ASSERT(FALSE);
	}
}
Exemple #3
0
/***********************************************************
catch key event
***********************************************************/
bool ChooseWorldGUI::HandleEnterKey (const CEGUI::EventArgs& e)
{
	const CEGUI::KeyEventArgs& we =
    static_cast<const CEGUI::KeyEventArgs&>(e);

	if(we.scancode == CEGUI::Key::Return)
	{	
		return HandleConnect(e);
	}

	return false;
}
Exemple #4
0
int base::TCPServer::Listen() {
	int res = listen(_sockfd, 1024);
	if (res < 0) {
		// perror("listen error");
		return 1;
	}

	for (; ; ) {
		socket_t clientfd;
		struct sockaddr_in client_addr;
		socklen_t len = sizeof(client_addr);
		clientfd = accept(_sockfd, (struct sockaddr *)&client_addr, &len);
		if (clientfd < 0) {
			// perror("accept error");
			return 1;
		}
		HandleConnect(clientfd);
	}
	return 0;
}
Exemple #5
0
BOOL CTcpClient::ProcessNetworkEvent(SHORT events)
{
	BOOL bContinue = TRUE;

	if(bContinue && events & POLLERR)
		bContinue = HandleClose(events);

	if(bContinue && !IsConnected())
		bContinue = HandleConnect(events);

	if(bContinue && events & POLLIN)
		bContinue = HandleRead(events);

	if(bContinue && events & POLLOUT)
		bContinue = HandleWrite(events);

	if(bContinue && events & _POLL_HUNGUP_EVENTS)
		bContinue = HandleClose(events);

	return bContinue;
}
BOOL CUdpClient::ProcessNetworkEvent()
{
	BOOL bContinue = TRUE;
	WSANETWORKEVENTS events;
	
	int rc = ::WSAEnumNetworkEvents(m_soClient, m_evSocket, &events);

	if(rc == SOCKET_ERROR)
		bContinue = HandleError();

	if(bContinue && events.lNetworkEvents & FD_READ)
		bContinue = HandleRead(events);

	if(bContinue && events.lNetworkEvents & FD_WRITE)
		bContinue = HandleWrite(events);

	if(m_bAsyncConnect && bContinue && events.lNetworkEvents & FD_CONNECT)
		bContinue = HandleConnect(events);

	if(bContinue && events.lNetworkEvents & FD_CLOSE)
		bContinue = HandleClosse(events);

	return bContinue;
}
Exemple #7
0
bool CNetServerWorker::RunStep()
{
	// Check for messages from the game thread.
	// (Do as little work as possible while the mutex is held open,
	// to avoid performance problems and deadlocks.)
	
	m_ScriptInterface->GetRuntime()->MaybeIncrementalGC(0.5f);
	
	JSContext* cx = m_ScriptInterface->GetContext();
	JSAutoRequest rq(cx);

	std::vector<std::pair<int, CStr> > newAssignPlayer;
	std::vector<bool> newStartGame;
	std::vector<std::pair<CStr, int> > newPlayerReady;
	std::vector<bool> newPlayerResetReady;
	std::vector<std::string> newGameAttributes;
	std::vector<u32> newTurnLength;

	{
		CScopeLock lock(m_WorkerMutex);

		if (m_Shutdown)
			return false;

		newStartGame.swap(m_StartGameQueue);
		newPlayerReady.swap(m_PlayerReadyQueue);
		newPlayerResetReady.swap(m_PlayerResetReadyQueue);
		newAssignPlayer.swap(m_AssignPlayerQueue);
		newGameAttributes.swap(m_GameAttributesQueue);
		newTurnLength.swap(m_TurnLengthQueue);
	}

	for (size_t i = 0; i < newAssignPlayer.size(); ++i)
		AssignPlayer(newAssignPlayer[i].first, newAssignPlayer[i].second);

	for (size_t i = 0; i < newPlayerReady.size(); ++i)
		SetPlayerReady(newPlayerReady[i].first, newPlayerReady[i].second);

	if (!newPlayerResetReady.empty())
		ClearAllPlayerReady();

	if (!newGameAttributes.empty())
	{
		JS::RootedValue gameAttributesVal(cx);
		GetScriptInterface().ParseJSON(newGameAttributes.back(), &gameAttributesVal);
		UpdateGameAttributes(&gameAttributesVal);
	}

	if (!newTurnLength.empty())
		SetTurnLength(newTurnLength.back());

	// Do StartGame last, so we have the most up-to-date game attributes when we start
	if (!newStartGame.empty())
		StartGame();

	// Perform file transfers
	for (size_t i = 0; i < m_Sessions.size(); ++i)
		m_Sessions[i]->GetFileTransferer().Poll();

	// Process network events:

	ENetEvent event;
	int status = enet_host_service(m_Host, &event, HOST_SERVICE_TIMEOUT);
	if (status < 0)
	{
		LOGERROR("CNetServerWorker: enet_host_service failed (%d)", status);
		// TODO: notify game that the server has shut down
		return false;
	}

	if (status == 0)
	{
		// Reached timeout with no events - try again
		return true;
	}

	// Process the event:

	switch (event.type)
	{
	case ENET_EVENT_TYPE_CONNECT:
	{
		// Report the client address
		char hostname[256] = "(error)";
		enet_address_get_host_ip(&event.peer->address, hostname, ARRAY_SIZE(hostname));
		LOGMESSAGE("Net server: Received connection from %s:%u", hostname, (unsigned int)event.peer->address.port);

		// Set up a session object for this peer

		CNetServerSession* session = new CNetServerSession(*this, event.peer);

		m_Sessions.push_back(session);

		SetupSession(session);

		ENSURE(event.peer->data == NULL);
		event.peer->data = session;

		HandleConnect(session);

		break;
	}

	case ENET_EVENT_TYPE_DISCONNECT:
	{
		// If there is an active session with this peer, then reset and delete it

		CNetServerSession* session = static_cast<CNetServerSession*>(event.peer->data);
		if (session)
		{
			LOGMESSAGE("Net server: Disconnected %s", DebugName(session).c_str());

			// Remove the session first, so we won't send player-update messages to it
			// when updating the FSM
			m_Sessions.erase(remove(m_Sessions.begin(), m_Sessions.end(), session), m_Sessions.end());

			session->Update((uint)NMT_CONNECTION_LOST, NULL);

			delete session;
			event.peer->data = NULL;
		}

		break;
	}

	case ENET_EVENT_TYPE_RECEIVE:
	{
		// If there is an active session with this peer, then process the message

		CNetServerSession* session = static_cast<CNetServerSession*>(event.peer->data);
		if (session)
		{
			// Create message from raw data
			CNetMessage* msg = CNetMessageFactory::CreateMessage(event.packet->data, event.packet->dataLength, GetScriptInterface());
			if (msg)
			{
				LOGMESSAGE("Net server: Received message %s of size %lu from %s", msg->ToString().c_str(), (unsigned long)msg->GetSerializedLength(), DebugName(session).c_str());

				HandleMessageReceive(msg, session);

				delete msg;
			}
		}

		// Done using the packet
		enet_packet_destroy(event.packet);

		break;
	}

	case ENET_EVENT_TYPE_NONE:
		break;
	}

	return true;
}
bool NetServer::ServerStep()
{
	// use lastTic to keep track of how many tics per second we have; control "tics per second"
	// perform any periodic, timed events here

	ENetEvent event;
	int status = enet_host_service(server, &event, HOST_TIMEOUT);

	if (status < 0) return false; // ERROR happened! Server shut down!	

	TimedEvent();

	if (status == 0) return true; // nothing to do, try again later

	switch(event.type)
	{
	case ENET_EVENT_TYPE_CONNECT:
		{
			printf ("A new client (%d) connected from %x:%u.\n", 
				event.peer,
				event.peer -> address.host,
				event.peer -> address.port);

			client *c = new client;
			char hostname[256] = "error";
			enet_address_get_host_ip(&event.peer->address, hostname, 256);
			printf("%s connected\n", hostname);

			if (event.peer != master)
			{
				c->hostname = string(hostname);
				c->peer = event.peer;
				c->state = ST_AUTH;

				// associate peer with the client object for them
				event.peer->data = c;

				// Call HandleConnect method of the game logic
				// if it returns false, then that means connection denied, otherwise specifies state client is in
				// also add to list of clients
				if (HandleConnect(event.peer)) {
					bool client_added = false;
					for (size_t i = 0; i < clients.size(); i++) {
						if (clients.at(i)->state == ST_EMPTY) {
							clients.at(i) = c;
							client_added = true;
							break;
						}
					}
					if (!client_added)
						clients.push_back(c);
				} else {
					enet_peer_disconnect(event.peer, 121);
				}
			} else {
				MasterCheckin();
			}
			break;
		}

	case ENET_EVENT_TYPE_DISCONNECT:
		{
			if (event.peer != master) {
				printf ("%d disconnected.\n", event.peer);

				// Call HandleDisconnect method some form of id for the connection
				HandleDisconnect(323, event.peer);

				// free up this client slot for reuse
				((client*) event.peer->data)->state = ST_EMPTY;
			} else {
				printf ("Master timed out.\n");
				master = 0;
			}
			break;
		}
	case ENET_EVENT_TYPE_RECEIVE:
		{
			char hostname[256] = "error";
			enet_address_get_host_ip(&event.peer->address, hostname, 256);
			printf("receiving packet.\n");
			printf ("A packet of length %u ",
				event.packet -> dataLength);
			printf("containing %s ",
				event.packet -> data);
			printf("was received from %s ",
				hostname);
			printf("on channel %u.\n",
				event.channelID);
			/*printf ("A packet of length %u containing %s was received from %s on channel %u.\n",
			event.packet -> dataLength,
			event.packet -> data,
			((client*)event.peer -> data)->hostname.c_str(),
			event.channelID);*/

			client *c = (client*) event.peer->data;

			// Call Packet Handler to deal with packets, and send a response
			HandlePacket(event.packet->data, event.packet->dataLength, event.peer);

			if (event.packet->referenceCount == 0) enet_packet_destroy(event.packet);
			break;
		}
	default:
		break;
	}
	enet_host_flush(server);
	return true;
}
Exemple #9
0
// Update
void _Server::Update(double FrameTime) {
	//if(std::abs(std::fmod(Time, 1.0)) >= 0.99)
	//	std::cout << "Server: O=" << ObjectManager->Objects.size() << " B=" << BattleManager->Objects.size() << std::endl;

	// Update network
	Network->Update(FrameTime);

	// Get events
	_NetworkEvent NetworkEvent;
	while(Network->GetNetworkEvent(NetworkEvent)) {

		switch(NetworkEvent.Type) {
			case _NetworkEvent::CONNECT:
				HandleConnect(NetworkEvent);
			break;
			case _NetworkEvent::DISCONNECT:
				HandleDisconnect(NetworkEvent);
			break;
			case _NetworkEvent::PACKET:
				HandlePacket(*NetworkEvent.Data, NetworkEvent.Peer);
				delete NetworkEvent.Data;
			break;
		}
	}

	// Update objects
	ObjectManager->Update(FrameTime);

	// Spawn battles
	for(auto &BattleEvent : BattleEvents)
		StartBattle(BattleEvent);

	BattleEvents.clear();

	// Update maps
	MapManager->Update(FrameTime);

	// Update battles
	BattleManager->Update(FrameTime);

	// Check if updates should be sent
	if(Network->NeedsUpdate()) {
		Network->ResetUpdateTimer();
		if(Network->GetPeers().size() > 0) {

			// Send object updates
			for(auto &Map : MapManager->Objects) {
				Map->SendObjectUpdates();
			}
		}
	}

	// Wait for peers to disconnect
	if(StartDisconnect) {
		Network->DisconnectAll();
		StartDisconnect = false;
		StartShutdown = true;
	}
	else if(StartShutdown && Network->GetPeers().size() == 0) {
		Done = true;
	}

	TimeSteps++;
	Time += FrameTime;

	// Update scripting environment
	Scripting->InjectTime(Time);

	// Update clock
	Clock += FrameTime * MAP_CLOCK_SPEED;
	if(Clock >= MAP_DAY_LENGTH)
		Clock -= MAP_DAY_LENGTH;

	// Update autosave
	SaveTime += FrameTime;
	if(SaveTime >= DEFAULT_AUTOSAVE_PERIOD) {
		SaveTime = 0;

		// Save players
		for(auto &Object : ObjectManager->Objects) {
			Save->SavePlayer(Object);
		}
	}
}
Exemple #10
0
void Client::HandleConnect_Base(NetworkErrorCode _status) { HandleConnect(_status); }
Exemple #11
0
Login::Login(std::shared_ptr<MultiplayerMenu> multiplayerMenu)
: menu_(multiplayerMenu), text_("connecting ..."), cancel_("Cancel"), socket_(new Socket) {
	cancel_.Connect([this]() { OnCancel(); });
	socket_->Connect(server_, port_, [this]() { HandleConnect(); });
	cancel_.CenterAt(0, 200);
}