void cServer::OnConnectionAccepted(cSocket & a_Socket) { if (!a_Socket.IsValid()) { return; } const AString & ClientIP = a_Socket.GetIPString(); if (ClientIP.empty()) { LOGWARN("cServer: A client connected, but didn't present its IP, disconnecting."); a_Socket.CloseSocket(); return; } LOGD("Client \"%s\" connected!", ClientIP.c_str()); cClientHandle * NewHandle = new cClientHandle(&a_Socket, m_ClientViewDistance); if (!m_SocketThreads.AddClient(a_Socket, NewHandle)) { // For some reason SocketThreads have rejected the handle, clean it up LOGERROR("Client \"%s\" cannot be handled, server probably unstable", ClientIP.c_str()); a_Socket.CloseSocket(); delete NewHandle; return; } cCSLock Lock(m_CSClients); m_Clients.push_back(NewHandle); }
bool cSocketThreads::cSocketThread::SendDataThroughSocket(cSocket & a_Socket, AString & a_Data) { // Send data in smaller chunks, so that the OS send buffers aren't overflown easily while (!a_Data.empty()) { size_t NumToSend = std::min(a_Data.size(), (size_t)1024); int Sent = a_Socket.Send(a_Data.data(), NumToSend); if (Sent < 0) { int Err = cSocket::GetLastError(); if (Err == cSocket::ErrWouldBlock) { // The OS send buffer is full, leave the outgoing data for the next time return true; } // An error has occured return false; } if (Sent == 0) { a_Socket.CloseSocket(); return true; } a_Data.erase(0, Sent); } return true; }
int main(int argc, char** argv) { // Attach to various terminal signals signal(SIGABRT, &Sighandler); signal(SIGTERM, &Sighandler); signal(SIGINT, &Sighandler); // Initialize our Database if(!Database::Init()) return 1; Maps::Load(0); // TODO: Check how many maps we have and load them all at once, for now loading default 0 will work. // Open the socket if(!Listener.Open(serverPort)) return 2; // Bind our socket if(!Listener.Bind()) return 4; // Set us to listen if(!Listener.Listen()) return 3; while(Running) { // Do we have a connection? if(Listener.HasData()) { printf("Yay, new person\n"); // Yes we do cSocket *newfd = Listener.Accept(); // TODO: Currently setting ID to IP Players::InsertPlayer(newfd->IP(), new cPlayer(newfd)); } // Check for disconnected people mDeletions.lock(); if(Deletions.size() > 0) // yay, people to remove { for(u32 a = 0; a < Deletions.size(); ++a) { memset(&Deletions[a], sizeof(Deletions[a]), 0); delete Deletions[a]; } Deletions.clear(); } mDeletions.unlock(); } // Shutdown our Database Database::Shutdown(); // Shutdown the maps Maps::Shutdown(); return 0; } // end of int main
void ServerIO_Thread(void*) { while(alive) { sock.getData(); if(sock.len > 1) { //con.addText(sock.recv_buf,sock.len,true); parseText(sock.recv_buf); //con.draw(); } } _endthread(); }