bool CTcp::Start(int port , tcpHandler handler) { bool ret = FALSE; MySocket socket; socket.Create(); if (socket.Bind(port)) { m_sock = socket; ARGV_LIST* argv = new ARGV_LIST; argv->handler = handler; argv->s = socket; argv->lpParameter = this; listen(socket,25); _beginthread(Listen,0,argv); ret = TRUE; } return ret; }
BOOL TcpComm::Send( MySocket& sock, ULONG targetIP, const LPBYTE pData, DWORD dwSize ) { IN_ADDR addr; addr.S_un.S_addr = targetIP; ByteBuffer sendByteBuffer; sendByteBuffer.Alloc(dwSize); memcpy((LPBYTE)sendByteBuffer, pData, dwSize); BOOL bSentOK = FALSE; int iSent = sock.SendAll((LPBYTE)sendByteBuffer, sendByteBuffer.Size()); if (iSent) { bSentOK = TRUE; } else { sock.Close(); if (! Connect(targetIP, sock)) { debugLog(_T("connect %x %s failed"), targetIP, a2t(inet_ntoa(addr))); return FALSE; } } return bSentOK; }
BOOL TcpComm::Connect( ULONG targetIP, MySocket& sock ) { #ifdef _DEBUG g_ConfigInfo.nPort = 8081; #endif sock.Close(); if (! sock.Create(TRUE)) { errorLogE(_T("create socket failed.")); return FALSE; } if (! sock.Connect(targetIP, g_ConfigInfo.nPort, 10)) { errorLog(_T("connect [%u] failed"), targetIP); return FALSE; } int value = 65535; if (0 != setsockopt(sock, SOL_SOCKET, SO_RCVBUF, (char*)&value, sizeof(value))) { errorLog(_T("setsockopt rcvbuf failed.WE%d"), ::WSAGetLastError()); } value = 65535; if (0 != setsockopt(sock, SOL_SOCKET, SO_SNDBUF, (char*)&value, sizeof(value))) { errorLog(_T("setsockopt sndbuf failed.WE%d"), ::WSAGetLastError()); } return TRUE; }
int main() { /* 初始化协议 */ StartSocket(); GameProtocal gameProtocal; clientMgr.AttachProtocal(&gameProtocal); gameProtocal.AttachManager(&clientMgr); /* 开启监听 */ sockSrv.Bind(MYPORT); sockSrv.Listen(); clientMgr.AddServer(&sockSrv); cout << "Now Listenning..." << endl; // 开启服务器发包线程,传送数据到 ThreadParam para; PThreadParam pp = ¶ pp->mgr = &clientMgr; #ifdef WIN32 DWORD threadID; CreateThread(0, 0, LPTHREAD_START_ROUTINE(ThreadSend), pp,NULL, &threadID); #else pthread_t threadID; pthread_create(&threadID, NULL, ThreadSend, (void*)pp); //signal(SIGALRM ,HeartBeatFun ); /* alarm clock timeout */ #endif // 主循环 while ( true ) { int len = sizeof(sockaddr); int sockConn; /* 测试accept返回的socket */ if ( -1 == (sockConn = sockSrv.Accept(&SockConn)) ){ exit(1); } /* 连接成功,创建新的客户socket以及线程,传送数据到thread */ ThreadParam para; PThreadParam pp = ¶ para.sock = &SockConn; para.mgr = &clientMgr; /* 开启客户线程 */ #ifdef WIN32 CloseHandle(CreateThread(0, 0, LPTHREAD_START_ROUTINE(ThreadClient), pp,NULL, &threadID) ); #else pthread_t threadID; pthread_create(&threadID, NULL, ThreadClient, (void*)pp); #endif } /* 清场 */ sockSrv.Close(); DestroySocket(); return 0; }
int main(){ MySocket s; SocketAddress a("localhost", 8080); s.Bind(&a); printf("Binded succesfully\n"); Run(&s); return 0; }
void ThreadServer::incomingConnection() { MySocket * soc = new MySocket(); if (setNewSocket(soc)) { soc->moveToThread(handler.getThread()); QObject::connect(soc,&MySocket::sentDiscon,this,&ThreadServer::removeThread); qDebug() << "New Connect Id:" << soc->socketDescriptor() << "\t\t" << "in Thread :" << QThread::currentThreadId(); } else delete soc; }
void *child(void *arg) { MySocket *client = (MySocket *) arg; bool requestActive = true; while (requestActive) { HTTPRequest *request = new HTTPRequest(client, PORT); HTTPResponse *response = new HTTPResponse(); IptvService *service = new IptvService(); if (!request->readRequest()) { // XXX FIXME throw an exception break; } else if (request->isHead()) { service->head(request, response); client->write(response->response()); } else if (request->isGet()) { service->get(request, response); client->write(response->response()); shared_ptr<BlockingQueue<string>> queue = shared_ptr<BlockingQueue<string>>(new BlockingQueue<string>()); struct ThreadData *threadData = new struct ThreadData; threadData->queue = queue; threadData->service = service; pthread_t tid; pthread_create(&tid, NULL, streamService, threadData); pthread_detach(tid); try { string data; while (true) { data = queue->popFront(); HttpUtils::writeChunk(client, data.c_str(), data.length()); } } catch (SocketWriteError swe) { requestActive = false; } catch (...) { // swallow it } queue->close(); } delete response; delete request; } client->close(); delete client; return NULL; }
MySocket* MySocket::Accept() { socklen_t len = sizeof(c_sockAddr); MySocket* tmpSocket = new MySocket(); printf("Ready to Accept socketId is [%d], port is [%d]\n", m_socketId, m_port); int clientId = accept(m_socketId, (struct sockaddr*)&c_sockAddr, &len); //int clientId = accept(m_socketId, (struct sockaddr*)&c_sockAddr, &len); printf("Accept Ok, clientId is [%d]\n", clientId); if (clientId < 0){ return nullptr; } tmpSocket->SetSocketId(clientId); return tmpSocket; }
int EchoServer::Run() { int ret = m_ptSocket->Bind(); printf("EchoServer::Bind Result[%d]\n", ret); ret = m_ptSocket->Listen(); printf("EchoServer::Listen Result[%d]\n", ret); MySocket* tmpSocket = m_ptSocket->Accept(); while (1){ char* data = tmpSocket->Read(); printf("Read From Client [%s]\n", data); tmpSocket->Write(data, strlen(data)); } }
void HeartBeatFun(int id) { for (int i = 0; i < clientMgr.GetNum(); i++) { MySocket *pSock = clientMgr.GetClient(i); if (pSock->IsLiving()) { pSock->m_isLiving = false; } else { clientMgr.GetProtocal()->UserExit(pSock); } } cout << "HeartBeat!" << endl; }
void MessagesSender::iniciarPartida(string puerto,string nombreUsuario){ MySocket* socketServidor; MySocket* socketCliente; Jugador *jug1,*jug2; QMutex mutex; jug1=new Jugador(COLOR_ROJO); jug2=new Jugador(COLOR_BLANCO); jug1->setNombre(nombreUsuario); try{ socketServidor=new MySocket(puerto); socketServidor->setFlags(O_NONBLOCK); socketServidor->listen(1); int i,j,indiceMensaje,bytes; string nombreJugador1; char firmaDelProtocolo[TAMANIO_FIRMA_DEL_PROTOCOLO+1]; char nombreDelJugador[TAMANIO_NOMBRE_JUGADOR+1]; char mensaje[BUFFER+1]; char mensajeRecibido[BUFFER+1]; int tamanioNombreJugador; cout<<"Esperando jugador..."<<endl; esperarConecciones=true; while( (socketCliente=socketServidor->accept())==nullptr ) { if(!esperarConecciones){ estaConectado=false; delete socketServidor; cout<<"Aqui"<<endl; return; } } mensaje[0]=FIRMA_DEL_PROTOCOLO[0]; mensaje[1]=FIRMA_DEL_PROTOCOLO[1]; mensaje[2]=INICIO_PARTIDA; mensaje[3]=VERSION_DEL_PROTOCOLO; nombreJugador1=jug1->getNombre(); indiceMensaje=4; for(i=0,j=nombreJugador1.size();i<j;i++){ mensaje[indiceMensaje++]=nombreJugador1.at(i); } mensaje[indiceMensaje]=0; socketCliente->write(mensaje,indiceMensaje); bytes=socketCliente->read(mensajeRecibido,BUFFER); memcpy(firmaDelProtocolo,mensajeRecibido,2); firmaDelProtocolo[TAMANIO_FIRMA_DEL_PROTOCOLO]='\0'; memcpy(nombreDelJugador,&mensajeRecibido[2],tamanioNombreJugador=bytes-2); nombreDelJugador[tamanioNombreJugador]='\0'; cout<<"Firma del protocolo:"<<firmaDelProtocolo<<endl; cout<<"Nombre del jugador 2:"<<nombreDelJugador<<endl; if(strncmp(firmaDelProtocolo,FIRMA_DEL_PROTOCOLO,2)!=0){ estaConectado=false; cout<<"No se recibio la bandera adecuada"<<endl; delete socketCliente; return; } /*cout<<socketCliente<<endl; cout<<socketCliente->getIp()<<endl; jug2->setHost(socketCliente->getIp()); cout<<"IP:"<< jug2->getHost()<<endl; cout<<"Puerto:"<<socketCliente->getPort()<<endl;*/ jug2->setNombre(string(nombreDelJugador)); mutex.lock(); socketCliente->setFlags(O_NONBLOCK); MessagesSender::socketCliente=socketCliente; MessagesSender::socketServidor=socketServidor; Tablero tablero(jug1,jug2); ::tablero=move(tablero); mutex.unlock(); estaConectado=true; }catch(SocketException& ex){ cout<<ex.getMessage()<<endl; } }
// return winner_Message(turn^=3); // } int game::start_network(int gameMode, MySocket& player, game& gameData) { char stone[3][3]={"","●","○"}; // initialize stone map(); //turn==1: white, turn==2: black int totalturn = 0, turn2 = 0; //turn2: flag for two turn turn = 2; //first turn is black setting::Cursor(); first_move(&y, &x); //first randum move while(decideWinner() == 0) //yet winner occur { if(turn2==1) {//after place two stones //change player if (turn == 2) turn = 1; else turn = 2; turn2=0; //initialize flag } else turn2++; setting::gotoxy(0, 21); cout<<stone[turn]<<"'s turn"; while(!put(y, x, turn)) // { //go(&y, &x); // if (gameMode == SE){ if (turn == 2){ input(&y, &x, turn);//input position to move player.SendData(&gameData); } else if (turn == 1){ player.RecvData(&gameData); } } if (gameMode == CL){ if (turn == 2){ player.RecvData(&gameData); } else if (turn == 1){ input(&y, &x, turn);//input position to move player.SendData(&gameData); } } } if(turn==1) //turn==white, print num of white stone { setting::gotoxy(42, 0); cout <<"White Stone : "<< ++turn1Cnt; } else //turn==black, print num of black stone { setting::gotoxy(42, 1); cout << "Black Stone : "<<++turn2Cnt; } setting::gotoxy(42, 2); cout <<"Total : "<<++totalturn; } return winner_Message(turn^=3); }