void CItem::SetAccessorySocketMaxGrade(int iMaxGrade) { SetSocket(1, MINMAX(0, iMaxGrade, ITEM_ACCESSORY_SOCKET_MAX_NUM)); }
int Connection::ConnectTimeout(const std::string& ip,const std::string& port,int time_out) { addrinfo *res=NULL; int flags; //LockSelf(); if (!(_fd<0)){ ::close(_fd); } int socket_fd; if ((socket_fd = socket(PF_INET, SOCK_STREAM, 0)) < 0) goto ERROR; //WEBSEARCH_DEBUG((LM_DEBUG,"ip:%s,port:%d\n",ip.c_str(),atoi(port.c_str()))); flags=fcntl(socket_fd,F_GETFL,0); fcntl(socket_fd,F_SETFL,flags|O_NONBLOCK); static addrinfo hints = { 0, AF_INET, SOCK_STREAM, IPPROTO_TCP, 0, NULL, NULL, NULL }; if (getaddrinfo(ip.c_str(),port.c_str(), &hints, &res)){ ::close(socket_fd); goto ERROR; } if (connect(socket_fd, (struct sockaddr*)((sockaddr_in *)res->ai_addr), sizeof(sockaddr_in)) < 0) { //fprintf(stderr,"connect summary error\n"); //sSocketHandle * hdle = new sSocketHandle(INVALID_FD); //m_sock_fd[i] = hdle; //::close(socket_fd); //goto ERROR; fd_set set; FD_ZERO(&set); FD_SET(socket_fd, &set); struct timeval timeout; timeout.tv_sec = 0; timeout.tv_usec = time_out*1000; if ( select(socket_fd+1, NULL, &set, NULL, &timeout) > 0 ) { //conn_ok = true; }else { ::close(socket_fd); goto ERROR; } } if (SetSocket(socket_fd, O_NONBLOCK)) { ::close(socket_fd); goto ERROR; } _debug("connect ok,ip:%s,port:%d\n",ip.c_str(),atoi(port.c_str())); _fd = socket_fd; //UnLockSelf(); if (res) free(res); return 0; ERROR: //UnLockSelf(); _debug("connect faild,ip:%s,port:%d\n",ip.c_str(),atoi(port.c_str())); _fd =INVALID_FD; if (res) free(res); return -1; }
int CSTATEngine::SendCommand(CSTATScriptCommand *pSendCommand, CSTATScriptCommand **ppRecvCommand) { int ret = GENERAL_FAILURE; CSTATScriptCommand tempCommand; tempCommand.cCommandID = pSendCommand->cCommandID; // the first instance of a 'R' or 'T' command, it could set a data socket instead of a file if(pSendCommand->cCommandID=='T' || pSendCommand->cCommandID=='R') { if(dataSocket==NULL && settingSocket && pSendCommand->Command()!=NULL) { char *comma = strchr(pSendCommand->Command(),','); if(!(comma > pSendCommand->Command() + pSendCommand->Length())) { switch(pSendCommand->cCommandID) { case 'R': { char *colon = strchr(comma,':'); if(colon==NULL) break; comma += 1; std::string ipAdd( comma, colon - comma ); colon += 1; std::string ipPort( colon ); ret = SetSocket(ipAdd.c_str() , atoi( ipPort.c_str() )); if(ret!=ITS_OK) { return ret; } break; } case 'T': { char *colon = strchr( pSendCommand->Command() , ':' ); if(colon==NULL) break; std::string ipAdd( pSendCommand->Command() , colon - pSendCommand->Command() ); colon += 1; if(comma < colon) break; std::string ipPort( colon , comma - colon ); ret = SetSocket(ipAdd.c_str() , atoi(ipPort.c_str())); if(ret!=ITS_OK) { return ret; } break; } } } } settingSocket=false; } // send the first command if ((ret = SendSingleCommand(pSendCommand, ppRecvCommand)) == ITS_OK) { // check our response - if Serial/Infra-red, need to break it down if (pComms->GetMaxPacketSize() != 0) { // break up the command into buffer-sized chunks if (pSendCommand->Length() > pComms->GetMaxPacketSize() || (dataSocket!=NULL && pSendCommand->cCommandID=='T')) { int i = 0; unsigned long offset = 0; unsigned long ulTotalWritten = 0; unsigned long AmountToWrite = pComms->GetMaxPacketSize(); unsigned long OriginalLength = pSendCommand->Length(); if(dataSocket==NULL) { int iWrites = pSendCommand->Length() / pComms->GetMaxPacketSize() + 1; Message("Writing %d bytes of data in %d separate writes...", OriginalLength, iWrites); for (i=0;i<iWrites;i++) { offset = i * pComms->GetMaxPacketSize(); if ((pSendCommand->Length() - offset) < pComms->GetMaxPacketSize()) AmountToWrite = (pSendCommand->Length() - offset); if (AmountToWrite) { //Sleep(100); // pause a bit for slower machines - probably doesn't need it but it can't hurt... // now send the command Message("Writing %d bytes from offset %d", AmountToWrite, offset); tempCommand.SetData(pSendCommand->Command() + ulTotalWritten, AmountToWrite); if ((ret = SendSingleCommand(&tempCommand, ppRecvCommand)) == ITS_OK) { //Message("%d bytes successfully written", AmountToWrite); } else return ret; ulTotalWritten += AmountToWrite; } } } else { //uses socket transmission char *pData = new char[AmountToWrite]; tempCommand.ulLength = (unsigned long) -1; if((ret = SendSingleCommand(&tempCommand, ppRecvCommand)) != ITS_OK) { delete [] pData; return ret; } while(true){ int AmountToWrite = pComms->GetMaxPacketSize(); ReadFromSocket(pData, &AmountToWrite ); if(AmountToWrite>=0) { Message("Writing %d bytes", AmountToWrite); tempCommand.SetData(pData , AmountToWrite); if ((ret = SendSingleCommand(&tempCommand, ppRecvCommand)) == ITS_OK) { //Message("%d bytes successfully written", AmountToWrite); } else { settingSocket=true; delete [] pData; return ret; } ulTotalWritten +=AmountToWrite; } else { eStopProcessing = STAT_PAUSE; break; } if(AmountToWrite==0) { break; } } delete [] pData; } // once completely sent, send an empty command to show that we've finished if(dataSocket == NULL ) { if (ulTotalWritten == OriginalLength) { // send the command that signals the end of our transmission Message("Sending completion command %c", tempCommand.cCommandID); tempCommand.SetData(NULL, 0); if ((ret = SendSingleCommand(&tempCommand, ppRecvCommand)) == ITS_OK) { //Message("Completion command successfully written"); } } else { Message("Incorrect number of bytes written - expected %ld got %ld", ulTotalWritten, OriginalLength); ret = E_BADNUMBERBYTES; } } } } } if (ret == ITS_OK) { // check our response - if Serial/Infra-red, need to break it down // if < STAT_BUFFERSIZE, nothing more to do // if not, we need to read in as many times as it takes to // assemble our complete command response if (pComms->GetMaxPacketSize() != 0) { if (ppRecvCommand && (*ppRecvCommand)->Length() > pComms->GetMaxPacketSize()) { unsigned long TotalLength = (*ppRecvCommand)->Length(); Message("%s: About to read %d bytes of data", GetConnection(eConnectType), TotalLength); // allocate memory to hold entire command char *pTemp = new char [TotalLength]; if (pTemp) { unsigned long ulTotalRead = 0; // empty packets tempCommand.SetData(NULL, 0); // now read data until we get an empty packet while((*ppRecvCommand)->Length()) { //Sleep(100); // pause a bit for slower machines - probably doesn't need it but it can't hurt... //Message("Sending continuation command %c", tempCommand.cCommandID); if ((ret = SendSingleCommand(&tempCommand, ppRecvCommand)) == ITS_OK) { if ((*ppRecvCommand)->Length()) { Message("%s to offset %d", pComms->Error(), ulTotalRead); //copy the data into the buffer memcpy(pTemp + ulTotalRead, (*ppRecvCommand)->Command(), (*ppRecvCommand)->Length()); if(dataSocket!=NULL) { int bytesSent = (int)(*ppRecvCommand)->Length(); WriteToSocket((*ppRecvCommand)->Command() , &bytesSent); if(bytesSent <= 0) { eStopProcessing = STAT_PAUSE; } } //increment the pointer to the end of the first chunk received ulTotalRead += (*ppRecvCommand)->Length(); } } else { settingSocket=true; delete [] pTemp; return ret; } } // make sure we got what we expected if (ulTotalRead == TotalLength) { // set our final response to the complete data transmission (*ppRecvCommand)->SetData(pTemp, ulTotalRead); //Message("Received successfully %ld bytes", ulTotalRead); } else { Message("Incorrect number of bytes read - expected %ld got %ld", ulTotalRead, TotalLength); ret = E_BADNUMBERBYTES; } // finished with it delete [] pTemp; } else { Message("Could not allocate %d bytes of memory", TotalLength); ret = E_OUTOFMEM; } } else if(dataSocket!=NULL && pSendCommand->cCommandID=='R') { int bytesSent = (int)(*ppRecvCommand)->Length(); WriteToSocket((*ppRecvCommand)->Command(), &bytesSent); } } } return ret; }
void NetSocket::ConnectServer( void ) { bool bFinished = false; //ResetAllData(); #ifdef WIN32 WSADATA Ws; if ( WSAStartup(MAKEWORD(2,0), &Ws) != 0 ) { cocos2d::CCLog("load winsocket error~"); } #endif do { m_iDescriptor = socket(AF_INET,SOCK_STREAM,IPPROTO_IP); if(m_iDescriptor <= 0) { this->CloseSocket(); cocos2d::CCLog("init socket failed"); break; } if(!SetSocket()) { this->CloseSocket(); cocos2d::CCLog("SetSocket() error"); break; } struct sockaddr_in sin; memset((void *)&sin, 0, sizeof(struct sockaddr_in)); sin.sin_family = AF_INET; sin.sin_port = htons(m_iServerPort); sin.sin_addr.s_addr = inet_addr(m_strServerIP.c_str());//IP #ifdef WIN32 unsigned long ul = 1; ioctlsocket(m_iDescriptor, FIONBIO, (unsigned long*)&ul); #else fcntl(m_iDescriptor, F_SETFL,fcntl(m_iDescriptor, F_GETFL)|O_NONBLOCK); // fcntl(st, F_SETFL,fcntl(st,F_GETFL,0)|O_NONBLOCK); //if (0 != pthread_create(&thID, NULL, _WorkThread, (void *)this)) break; #endif int connectResult=connect(m_iDescriptor, (struct sockaddr *)&sin, sizeof(struct sockaddr)); CCLog("connect result~~~~~~~~~~~~~~~~~:%d",connectResult); if(NET_SOCKET_ERROR == connectResult) { int select_return = TestingNet( 6 , 0, 2 ); // 6 char error = 0; #if WIN32 int errorlen = 0; #else socklen_t errorlen=sizeof(int); #endif switch( select_return ) { case 1: { getsockopt( m_iDescriptor,SOL_SOCKET, SO_ERROR, &error, &errorlen); if( error == 0 ) { bFinished = true; m_bIsConnecting = false; cocos2d::CCLog("connect ok"); } } break; case 0: cocos2d::CCLog("connect out of time"); break; case -1: cocos2d::CCLog("connect select error"); break; } }else if (connectResult==0){ char error = 0; #if WIN32 int errorlen = 0; #else socklen_t errorlen=sizeof(int); #endif getsockopt( m_iDescriptor,SOL_SOCKET, SO_ERROR, &error, &errorlen); if( error == 0 ) { bFinished = true; m_bIsConnecting = false; cocos2d::CCLog("connect ok"); } break; }else { break; } } while(false); if(!bFinished) { cocos2d::CCLog("start socket error"); this->CloseSocket(); ResetData(); } m_bIsConnected = bFinished; }
cReactorSession::cReactorSession(cTreeNodes* nodes, const char* sessionName) : cAbstractSession(), cTreeNodes(), cTreeNode(nodes, NULL, NULL) { SetSocket( -1 ); SetSessionName( sessionName ); }
UserConnection::~UserConnection() { SetSocket(0); account_id_ = 0xFFFFFFFF; }
CRoseClient::CRoseClient(tcp::socket &&_sock) : CNetwork_Asio(), crypt_() { SetSocket(std::move(_sock)); Recv(); ResetBuffer(); }
unsigned SocketdHandler::ThreadHandlerProc(void) { char recvbuf[DEFAULT_BUFLEN]; int recvbuflen = DEFAULT_BUFLEN; int iResult; auto boardManager = bbg::BoardManager::Instance(); isDone = false; while ( true ) { printf("Going for receive...\n"); iResult = recv(m_clientSocket, recvbuf, recvbuflen, 0); if (iResult > 0) { char* sbuf = (char*)malloc(sizeof(char)*iResult); memset(sbuf,0,iResult); memcpy(sbuf,&recvbuf[0],iResult); std::vector<string> listReceive = bbg::Util::GatherMessages(sbuf,iResult); int ctr = 0; for(auto itm : listReceive) { ctr++; auto requestData = new bbg::RequestData(); std::string ssbuf(sbuf); requestData->SetMessageData(itm); requestData->SetSocket((int)m_clientSocket); printf("Data Pushed: [socket=%d] [thread=%d] [loop=%d] %s \n", (int)m_clientSocket, GetCurrentThreadId(), ctr, itm.c_str()); requestDataManager->GrantWriterAccess(); requestDataManager->AddRequestData(requestData); requestDataManager->ReleaseWriterAccess(); } } if (iResult > 0) { printf("Bytes received: %d\n", iResult); std::vector<string> s = bbg::Util::Parse(recvbuf, " ",iResult); std::string action = s[0]; std::string loginId = ""; std::string sayMesg = ""; if (action.compare("LOGIN") == 0) { loginId = s[1]; printf("Login command: %s\n", loginId.c_str()); bbg::User* user = new bbg::User(); user->SetLoginId(loginId); boardManager->Create(user); } if (action.compare("SAY") == 0) { loginId = s[1]; sayMesg = s[2]; printf("Say command: user %s said \"%s\"\n", loginId.c_str(), sayMesg.c_str()); } if (action.compare("QUIT") == 0) { printf("Quit command: user %s \n", loginId.c_str()); isDone = true; } if (action.compare("SHUTDOWN") == 0) { isDone = true; printf("Server shutting down... \n"); } } else if (iResult == 0) { printf("Zero recv...\n"); isDone = true; closesocket(m_clientSocket); return 0; } else { printf("recv() failed with error: %d\n", WSAGetLastError()); int errCode = WSAGetLastError(); if (errCode==10054) { printf("10054 WSAECONNRESET: Connection reset by peer. Client disconnect.\n"); } else if (errCode==10058) { printf("10058 WSAESHUTDOWN : Cannot send after socket shutdown.\n"); } else if (errCode==10024) { printf("10024 WSAEMFILE : Too many open files. Too many open sockets. \n"); } else if (errCode==10048) { printf("10048 WSAEADDRINUSE : Address already in use. \n"); } else if (errCode==10050) { printf("10050 WSAENETDOWN : Network is down. \n"); } else if (errCode==10051) { printf("10051 WSAENETUNREACH : Network is unreachable.\n"); } else if (errCode==10052) { printf("10052 WSAENETRESET : Network dropped connection on reset.\n"); } else if (errCode==10055) { printf("10055 WSAENOBUFS : No buffer space available.\n"); } else if (errCode==10057) { printf("10057 WSAENOTCONN : Socket is not connected.\n"); } else if (errCode==10059) { printf("10059 WSAETOOMANYREFS : Too many references.\n"); } else if (errCode==10060) { printf("10060 WSAETIMEDOUT : Connection timed out.\n"); } else if (errCode==10061) { printf("10061 WSAECONNREFUSED : Connection refused.\n"); } else { printf("XXXXX UNDEFINED : Undefined error code / condition.\n"); } closesocket(m_clientSocket); isDone = true; break; } if (iResult == 0 || iResult == -1) { printf("Socket shutdown...\n"); iResult = shutdown(m_clientSocket, 1); if (iResult == SOCKET_ERROR) { printf("shutdown failed with error: %d\n", WSAGetLastError()); closesocket(m_clientSocket); isDone = true; } printf("Handler exiting...\n"); return 0; } } return 0; }
BOOL CNetDatagramSender::SetSocket(const char * c_szIP, WORD wPortIndex) { return SetSocket(inet_addr(c_szIP), wPortIndex); }