/* 更新新加入节点的前继节点的后继和后继的后继, * 以及新加入节点的后继节点的前继和前继的前继 */ void Join::update_neighbour() { theApp.scout<<"++++update neighbour++++"<<endl; int suc = peer->fingerTable.sucId; string sucIp = peer->fingerTable.sucIP; int sucPort = peer->fingerTable.sucPort; int pre = peer->fingerTable.preId; string preIp = peer->fingerTable.preIP; int prePort = peer->fingerTable.prePort; //更新前继节点的后继和后继的后继 stringstream ss1,ss2,ss3,ss4,ss5,ss6; ss1<<peer->fingerTable.port;ss2<<sucPort;ss3<<prePort; ss4<<peer->getId();ss5<<suc;ss6<<pre; string cmd = "newSuc " + peer->fingerTable.ip + " " + ss1.str() + " " + ss4.str() + " " + ss5.str() + " " + sucIp + " " + ss2.str(); CSocket socket; socket.Connect(preIp.c_str(),prePort); socket.WriteLine(cmd); socket.Close(); //更新后继节点的前继和前继的前继 cmd = "newPre " + peer->fingerTable.ip + " " + ss1.str() + " " + ss4.str() + " " + ss6.str() + " " + preIp + " " + ss3.str(); socket.Connect(sucIp.c_str(),sucPort); socket.WriteLine(cmd); socket.Close(); //更新前继的前继和后继的后继,他们只需要部分字段 suc_suc_pre_pre(); }
CJsonNode CReadJsonFromSocket::ReadMessage(CSocket& sock) { try { char read_buffer[READ_BUFFER_SIZE]; size_t bytes_read; do { s_ReadSocket(sock, read_buffer, READ_BUFFER_SIZE, &bytes_read); m_UTTPReader.SetNewBuffer(read_buffer, bytes_read); } while (!m_JSONReader.ReadMessage(m_UTTPReader)); } catch (...) { sock.Close(); throw; } if (m_UTTPReader.GetNextEvent() != CUTTPReader::eEndOfBuffer) { string server_address(sock.GetPeerAddress()); sock.Close(); NCBI_THROW_FMT(CNetStorageException, eIOError, "Extra bytes past message end while reading from " << server_address << " after receiving " << m_JSONReader.GetMessage().Repr() << '.'); } return m_JSONReader.GetMessage(); }
/* 更新新加入节点的前继的前继和后继的后继 * 通过向前继节点发出yourpre命令找出前继的前继,向后继节点发出yoursuc命令找出后继的后继 */ void Join::init_suc_suc_pre_pre() { //后继的后继 string cmd = "yoursuc"; CSocket socket; socket.Connect(peer->fingerTable.sucIP.c_str(),peer->fingerTable.sucPort); socket.WriteLine(cmd); string k = socket.ReadLine(); vector<string> s = Tool::Split(k," "); peer->fingerTable.sucsucIP = s[0]; peer->fingerTable.sucsucPort = atoi(s[1].c_str()); peer->fingerTable.sucsucId = atoi(s[2].c_str()); socket.Close(); theApp.scout<<"@@@@@@@@@@@@@@@"<<endl; //前继的前继 cmd = "yourpre"; socket.Connect(peer->fingerTable.preIP.c_str(),peer->fingerTable.prePort); socket.WriteLine(cmd); k = socket.ReadLine(); s = Tool::Split(k," "); peer->fingerTable.prepreIP = s[0]; peer->fingerTable.preprePort = atoi(s[1].c_str()); peer->fingerTable.prepreId = atoi(s[2].c_str()); socket.Close(); }
void SendNotification(CModule& module, const CString& sSender, const CString& sNotification, const CChan *pChannel) { // todo parse from m_sPushEndpoint bool bUseTLS = true; CString sHostname = "api.palaverapp.com"; unsigned short uPort = 443; CString sPath = "/1/push"; CString sJSON = "{"; sJSON += "\"message\": \"" + sNotification.Replace_n("\"", "\\\"") + "\""; sJSON += ",\"sender\": \"" + sSender.Replace_n("\"", "\\\"") + "\""; if (pChannel) { sJSON += ",\"channel\": \"" + pChannel->GetName().Replace_n("\"", "\\\"") + "\""; } sJSON += "}"; CSocket *pSocket = new CSocket(&module); pSocket->Connect(sHostname, uPort, bUseTLS); pSocket->Write("POST " + sPath + " HTTP/1.1\r\n"); pSocket->Write("Host: " + sHostname + "\r\n"); pSocket->Write("Authorization: Bearer " + GetToken() + "\r\n"); pSocket->Write("Connection: close\r\n"); pSocket->Write("User-Agent: ZNC\r\n"); pSocket->Write("Content-Type: application/json\r\n"); pSocket->Write("Content-Length: " + CString(sJSON.length()) + "\r\n"); pSocket->Write("\r\n"); pSocket->Write(sJSON); pSocket->Close(Csock::CLT_AFTERWRITE); module.AddSocket(pSocket); }
void CEditServer::OnGetcgi() { CSocket socket; CArchive*in; CArchive*out; CSocketFile* pFile; if (!socket.Create()) { return; } while (!socket.Connect(GETCGI_HOST,GETCGI_PORT)) { return; } pFile = new CSocketFile(&socket); in = new CArchive(pFile,CArchive::load); out = new CArchive(pFile,CArchive::store); CString str= "GET "; str += GETCGI_PATH; str += " HTTP/1.0\n\n"; out->Write(str, str.GetLength()); out->Flush(); CString line; int count=0; CString n,h,p; while (in->ReadString(line)) { int c=line.Find("####"); if (c==-1) continue; n=line.Left(c); line=line.Mid(c+4); c=line.Find("####"); if (c==-1) continue; h=line.Left(c); p=line.Mid(c+4); m_name[count]=n; m_host[count]=h; m_port[count]=atoi(p); count++; } if (count!=0) m_count=count; in->Close(); out->Close(); pFile->Close(); socket.Close(); delete out; delete in; delete pFile; UpdateList(); m_list.SetCurSel(0); return; }
BOOL TestConnection( LPCTSTR lpstrAddress, int nPort) { CSocket* pSocket; pSocket = new CSocket; ASSERT(pSocket); if (!pSocket->Create()) { delete pSocket; pSocket = NULL; return FALSE; } while (!pSocket->Connect( lpstrAddress, nPort)) { delete pSocket; pSocket = NULL; return FALSE; } pSocket->Close(); delete pSocket; return TRUE; }
/*更新前继的前继和后继的后继*/ void Join::suc_suc_pre_pre() { CSocket socket; socket.Connect(peer->fingerTable.sucsucIP.c_str(),peer->fingerTable.sucsucPort); string cmd = "set_your_pre_pre "; stringstream ss,ss1;ss<<peer->getId();ss1<<peer->getPort(); cmd += (ss.str() + " " + peer->getLocalIp() + " " + ss1.str()); socket.WriteLine(cmd); socket.Close(); socket.Connect(peer->fingerTable.prepreIP.c_str(),peer->fingerTable.preprePort); cmd = "set_your_suc_suc "; cmd += (ss.str() + " " + peer->getLocalIp() + " " + ss1.str()); socket.WriteLine(cmd); socket.Close(); }
int main(int argc, char* argv[]){ CSocket csocket; cout<<"Input The Server IP: "; cin>>serverIp; bool connect=csocket.Connect(serverIp,serverPort); csocket.SetBlocking(false); if(connect) { csocket.printTime();cout<<"connected"<<endl; uintptr_t threadId=_beginthread(recv,0,&csocket);//启动一个线程接收数据的线程 while(1) { char buf[BUF_LEN]; cin>>buf; csocket.Send(buf,strlen(buf)); if(csocket.IsExit()) { csocket.Close(); cout<<"exit success"<<endl; break; } } }else {
virtual void Close( void ){ if( !m_sock.IsInvalid() ){ m_sock.Close(); } if( m_bDeleteOnClose ){ m_bDeleteOnClose = false; delete this; } }
void CNetworkTalkClientDlg::OnBtnSend() { // TODO: Add your control notification handler code here CSocket sockClient; sockClient.Create(); sockClient.Connect(m_serverIPAddress,8000); g_serverIPAddress=m_serverIPAddress; sockClient.Send(m_sendText,m_sendText.GetLength()); sockClient.Close(); }
BOOL Listen() { #ifndef BATCH cout << "Listening: " << m_nAddr << ":" << m_nPort << ", with size: " << m_nNumOTThreads << endl; #endif if (!m_vSocket->Socket()) { goto listen_failure; } if (!m_vSocket->Bind(m_nPort, m_nAddr)) { goto listen_failure; } if (!m_vSocket->Listen()) { goto listen_failure; } for (int i = 0; i < 1; i++) // twice the actual number, due to double sockets for OT { CSocket sock; // cout << "New round! " << endl; if (!m_vSocket->Accept(sock)) { cerr << "Error in accept" << endl; goto listen_failure; } UINT threadID; sock.Receive(&threadID, sizeof(int)); if (threadID >= 1) { sock.Close(); i--; continue; } #ifndef BATCH cout << " (" << m_nPID << ") (" << threadID << ") connection accepted" << endl; #endif // locate the socket appropriately m_vSocket->AttachFrom(sock); sock.Detach(); } #ifndef BATCH cout << "Listening finished" << endl; #endif return TRUE; listen_failure: cout << "Listen failed" << endl; return FALSE; }
/** * listens and accepts connections on the server */ BOOL maliciousot::ConnectionManagerServer::setup_connection() { int num_connections = m_num_of_threads+1; cerr << "ConnectionManagerServer->setup_connection() started." << endl; // try to bind() and then listen if ((!m_sockets[0].Socket()) || (!m_sockets[0].Bind(m_port, m_address)) || (!m_sockets[0].Listen()) ) { goto listen_failure; } for(int i = 0; i<num_connections; i++) { //twice the actual number, due to double sockets for OT CSocket sock; // try: CSocket sock = accept() if(!m_sockets[0].Accept(sock)) { cerr << "Error in accept" << endl; goto listen_failure; } // cerr << "Server: accept succeded i = " << i << endl; // receive the other side thread id (the first thing that is sent on the socket) UINT threadID; sock.Receive(&threadID, sizeof(int)); // cerr << "Server: received threadID = " << threadID << endl; // ?? if(threadID >= num_connections) { // cerr << "Server: threadID >= num_connections, num_connections = " << num_connections << endl; sock.Close(); i--; continue; } // locate the socket appropriately // cerr << "Server: attaching socket to threadID = " << threadID << endl; m_sockets[threadID].AttachFrom(sock); sock.Detach(); } cerr << "ConnectionManagerServer->setup_connection() ended." << endl; return TRUE; listen_failure: cerr << "Listen failed" << endl; return FALSE; }
void CServerSocket::OnAccept(int nErrorCode) { CSingleLock sl(&m_csClientLock, TRUE); if( nErrorCode != 0 ) { TRACE("CServerSocket::OnAccept Error : %d\n", ::WSAGetLastError()); } else { // 빈 클라이언트를 찾는다 long nClientID = -1; long nMaxClient = (long)m_vecnbClientUsed.size(); for(long i = 0; i < nMaxClient; i++) { if(m_vecnbClientUsed[i] == FALSE) { nClientID = i; break; } } if(nClientID != -1) { if(m_vecpClient[nClientID] == NULL) m_vecpClient[nClientID] = new CClientSocket; CClientSocket *pCurSocket = m_vecpClient[nClientID]; pCurSocket->InitClient(m_nClientStartID + nClientID, m_hParentWnd, m_bUseReceiveCallback, m_pParentPtr, __CallbackDataReceive); m_vecnbClientUsed[nClientID] = TRUE; m_vecpClient[nClientID]->m_bConnect = TRUE; Accept(*pCurSocket, NULL, NULL); TRACE("CServerSocket::OnAccept\n"); if(m_hParentWnd) ::PostMessage(m_hParentWnd, UWM_SOCKET_UPDATE_CONNECTION, nClientID, EVT_CONSUCCESS); else __CallbackDataReceive(m_pParentPtr, nClientID, (BYTE *) - 1, EVT_CONSUCCESS); } else { CSocket Socket; Accept(Socket, NULL, NULL); Socket.ShutDown(); Socket.Close(); } } CAsyncSocket::OnAccept(nErrorCode); }
/* * 新节点加入拓扑时,需要把本属于它的key的hash从别的节点上转移过来 */ void Join::transfer_keys() { theApp.scout<<"++++ In the transfer key++++"<<endl; int sucId = peer->fingerTable.sucId; string sucIp = peer->fingerTable.sucIP; int sucPort = peer->fingerTable.sucPort; stringstream ss1,ss2,ss3,ss4;ss1<<peer->fingerTable.port;ss2<<peer->getId();ss3<<peer->fingerTable.preId; string cmd = "transfer_key " + peer->fingerTable.ip + " " + ss1.str() + " " + ss2.str() + " " + ss3.str(); if (sucId == peer->getId()) return; CSocket socket; socket.Connect(peer->fingerTable.sucIP.c_str(),peer->fingerTable.sucPort); socket.WriteLine(cmd); socket.Close(); }
int main(int argc, char* argv[]){ CSocket csocket; CPacket packet; int Command; char* sendMessage = new char[BUF_LEN]; parse_arguments(argc, argv); if (!s_serverPort) { cout<<"! The server port number is not defined."<<endl; usage(argv[0]); return 1; } if (!s_serverIP) { cout<<"! The server ip address is not defined"<<endl; usage(argv[0]); return 1; } bool connect=csocket.Connect(s_serverIP,s_serverPort); csocket.SetBlocking(false);//设置阻塞模式 //on_login_reply(!connect); if(connect) { cout<<"Connect the server success,please login."<<endl; show_prompt(); uintptr_t threadId=_beginthread(recv,0,&csocket);//启动一个线程接收数据的线程 while(1) { char buf[BUF_LEN]; cin>>buf; if (Command = packet.paseArguement(buf)) { memset(sendMessage, 0, 1024); sendMessage = packet.getCommand(Command); } show_prompt(); csocket.Send(sendMessage,sizeof(buf)); //csocket.Receive(64); if(csocket.IsExit()) { csocket.Close(); cout<<"exit success"<<endl; break; } } } else {
/* 更新环上每一个节点的FingerTable中的后继列表 */ void Join::update_others() { theApp.scout<<"++++update others++++"<<endl; int localId = peer->getId(); string localIp = peer->fingerTable.ip; int localport = peer->fingerTable.port; int suc = peer->fingerTable.sucId; string sucIp = peer->fingerTable.sucIP; int sucPort = peer->fingerTable.sucPort; stringstream ss,ss1;ss<<localport;ss1<<localId; string cmd = "new_node " + localIp + " " + ss.str() + " " + ss1.str(); CSocket socket; socket.Connect(sucIp.c_str(),sucPort); socket.WriteLine(cmd); socket.Close(); }
void CServer::Run() { Init(); CSocket sock; if(!sock.Socket()) return; if(!sock.Bind( CConfig::GetInstance()->GetPortPID(ID_SERVER), CConfig::GetInstance()->GetAddrPID(ID_SERVER)) ) return; cout << "listening.." << endl; sock.Listen(); CWireThread* pThreadWire = new CWireThread(); pThreadWire->Start(); CGateThread* pThreadGate = new CGateThread(); pThreadGate->Start(); if(!sock.Accept(m_sockMain)) return; if(!sock.Accept(m_sockOT)) return; sock.Close(); cout << "accepted sockets!" << endl; COTThread* pThreadOT = new COTThread(); pThreadOT->Start(); RunMainThread(); m_sockMain.Close(); pThreadOT->Wait(); m_sockOT.Close(); pThreadGate->Wait(); pThreadWire->Wait(); Cleanup(); delete pThreadOT; delete pThreadGate; delete pThreadWire; }
void CTestThreadedServer::Process(SOCK sock) { // CConn_SocketStream's destructor will take care of closing sock. CConn_SocketStream stream(sock, eTakeOwnership); string message; stream << "Hello!" << endl; stream >> message; stream << "Goodbye!" << endl; if (message == "Goodbye!") { m_ShutdownRequested = true; // try to connect back because the request is asynchronous. CSocket socket; if (socket.Connect("localhost", GetPort()) == eIO_Success) { socket.Close(); } } }
void main() { AfxSocketInit(); CSocket sock; int n = sock.Create(PORT1); if(!n) { cout << "创建句柄失败:" << GetLastError() << endl; return; } sock.Listen(); while (true) { CSocket socka; n = sock.Accept(socka); if(!n) { cout << "接受对方连接失败:" << GetLastError() << endl; return; } while (true) { char s[256]; n = socka.Receive(s,sizeof(s)); if(SOCKET_ERROR == n) { cout << "接收数据失败:" << GetLastError() << endl; break; } if(!n) { cout << "结束接收数据,句柄关闭!" << endl; break; } cout << s <<endl; } socka.Close(); } }
void ProcessConnection() { char buf[1024]; int n = m_socket->Recv(buf, sizeof(buf)); buf[n] = 0; char *s = FetchURL(buf); if (!strncmp(s, "/fav/list/", 10)) { SendList(); } else if (!strncmp(s, "/fav/open/", 10)) { OpenContact(s); } mir_free(s); m_socket->Close(); }
void CServerSocket::OnAccept(int nErrorCode) { // TODO: Add your specialized code here and/or call the base class // 4 接收客户端连接 CSocket client; Accept(client); // 5 接收文件... // 5.1 接收文件数据之前,首先接收文件信息 HEADER header={0}; if (!RecvData(client,(BYTE*)&header, sizeof(header))) { AfxMessageBox("接收文件信息失败!"); return; } // 5.2 接收文件数据 BYTE* pData=(BYTE*)malloc(header.nLen); if (!RecvData(client,pData,header.nLen)) { AfxMessageBox("接收文件数据失败!"); return; } // 5.3 保存到服务器 CFile file; CString strPath="C:/"; strPath+=header.szFile; file.Open(strPath, CFile::modeCreate|CFile::modeWrite); file.Write(pData,header.nLen); file.Close(); free(pData); // 6 关闭套接字 client.Close(); CAsyncSocket::OnAccept(nErrorCode); }
int _tmain(int argc, TCHAR* argv[], TCHAR* envp[]) { int nRetCode = 0; HMODULE hModule = ::GetModuleHandle(NULL); if (hModule != NULL) { // initialize MFC and print and error on failure if (!AfxWinInit(hModule, NULL, ::GetCommandLine(), 0)) { // TODO: change error code to suit your needs _tprintf(_T("Fatal Error: MFC initialization failed\n")); nRetCode = 1; } else { // TODO: code your application's behavior here. cout << "\t\t\t################# << CHIEC NON KY DIEU >> ################# " << endl << endl; KNClient x; x.InitChat(); x.RegisterName(); cout << "\n\n\t\t ***************** < Luat Choi > *****************\n"; cout << "1. Nguoi choi phai trai qua cac vong choi tuong duong voi so cau hoi cua chuong trinh.\n"; cout << "2. Khi den luot choi :\n \tdoan dung 1 chu cai -> nhan duoc so diem tuong duong so diem quay duoc.\n "; cout << "\tdoan dung o chu bi mat -> nhan duoc so diem x3.\n"; cout << "\n\t -----> nhan phim bat ky de bat dau tro choi : "; char k; cin >> k; fflush(stdin); system("cls"); cout << "\t\t\t################# << CHIEC NON KY DIEU >> ################# " << endl << endl; CSocket Client; char *str_r = new char[200]; Client.Receive(str_r, 200, 0); str_r[strlen(str_r)] = 0; if (strstr(str_r, "Exit")) { Client.Close(); return 0; } else { do { if (x.recieve()) //nếu trả về true mới được trl x.Answer(); else break; } while (1); } } } else {