BOOL CTcpClient::Start(LPCTSTR pszRemoteAddress, USHORT usPort, BOOL bAsyncConnect) { if(!CheckParams() || !CheckStarting()) return FALSE; BOOL isOK = FALSE; m_bAsyncConnect = bAsyncConnect; if(CreateClientSocket()) { if(FirePrepareConnect(m_dwConnID, m_soClient) != HR_ERROR) { if(ConnectToServer(pszRemoteAddress, usPort)) { if(CreateWorkerThread()) isOK = TRUE; else SetLastError(SE_WORKER_THREAD_CREATE, __FUNCTION__, ERROR_CREATE_FAILED); } else SetLastError(SE_CONNECT_SERVER, __FUNCTION__, ::WSAGetLastError()); } else SetLastError(SE_SOCKET_PREPARE, __FUNCTION__, ERROR_FUNCTION_FAILED); } else SetLastError(SE_SOCKET_CREATE, __FUNCTION__, ::WSAGetLastError()); if(!isOK) Stop(); return isOK; }
static BOOL Init(void) { struct system_t *pSystemInfo = &gSystemInfo; //初始化audio info结构体 if(!InitAudioStruct(pSystemInfo,TRUE)) { DBGE((TEXT("[System DLL] init struct err.\r\n"))); return FALSE; } if (!CreateClientSocket(9980)) { DBGE((TEXT("[System DLL] audio create client socket err.\r\n"))); return FALSE; } pSystemInfo->bInit = TRUE; BYTE buf[2] = {0x01,0x01}; SocketWrite(buf,2); DBGI((TEXT("\r\n[System DLL] Init OK time:"))); DBGI((TEXT(__TIME__))); DBGI((TEXT(" data:"))); DBGI((TEXT(__DATE__))); DBGI((TEXT("\r\n"))); return TRUE; }
/* *---------------------------------------------------------------------- * * TcpAsyncCallback -- * * Called by the event handler that CreateClientSocket sets up * internally for [socket -async] to get notified when the * asyncronous connection attempt has succeeded or failed. * *---------------------------------------------------------------------- */ static void TcpAsyncCallback( ClientData clientData, /* The socket state. */ int mask) /* Events of interest; an OR-ed combination of * TCL_READABLE, TCL_WRITABLE and * TCL_EXCEPTION. */ { CreateClientSocket(NULL, clientData); }
bool SocketClient::Open(bool force_open) { if (!force_open && IsConnected()) { LOG(WARNING) << "already connected"; return true; } Close(); fd_ = CreateClientSocket(peer_address_, peer_port_); if (nonblocking_) SetSocketNonblocking(fd_); return fd_ >= 0; }
void CServerSocket::SocketAccept( SOCKET ssocket,char* ip,int port ) { CCustomClientSocket * ClientSocket =NULL; Lock(); FreeCorpseClient(); ClientSocket = m_FreeClientPool.DeQueue(); if (ClientSocket != NULL) { ClientSocket = CreateClientSocket(); if(ClientSocket == NULL) { ClientSocket = new CCustomClientSocket; } } ClientSocket->SetSocketHandle(m_wCurrentHandle); ClientSocket->setRemoteAddress(ip); ClientSocket->setRemotePort(port); ClientSocket->SetIOCPHandle(m_hIOCP); ClientSocket->SetSocket(ssocket); ClientSocket->OnInitialize(); m_ActiveClientSocketList.push_back(ClientSocket); m_iClientCount ++; m_SessionMap[m_wCurrentHandle]=ClientSocket; if(ClientSocket->GetSocket() != INVALID_SOCKET) { if(CreateIoCompletionPort((HANDLE)ssocket,m_hIOCP,DWORD(ClientSocket),0)==0) { OnError((CCustomSocket *)ClientSocket,GetLastError()); ClientSocket->ForceClose(); } else { OnConnect((CCustomSocket *)ClientSocket); if (ClientSocket->GetSocket() != INVALID_SOCKET) { ClientSocket->PrepareRecv(ClientSocket->GetBlock(true)); } } } ClientSocket = NULL; do { m_wCurrentHandle++; if(m_wCurrentHandle < 1000) { m_wCurrentHandle = 1000; }}while (m_SessionMap.find(m_wCurrentHandle)!= m_SessionMap.end()); Unlock(); }
BOOL CUdpCast::Start(LPCTSTR lpszRemoteAddress, USHORT usPort, BOOL bAsyncConnect, LPCTSTR lpszBindAddress) { if(!CheckParams() || !CheckStarting()) return FALSE; PrepareStart(); m_ccContext.Reset(); BOOL isOK = FALSE; HP_SOCKADDR bindAddr(AF_UNSPEC, TRUE); if(CreateClientSocket(lpszRemoteAddress, usPort, lpszBindAddress, bindAddr)) { if(BindClientSocket(bindAddr)) { if(FirePrepareConnect(m_soClient) != HR_ERROR) { if(ConnectToGroup(bindAddr)) { if(CreateWorkerThread()) { isOK = TRUE; } else SetLastError(SE_WORKER_THREAD_CREATE, __FUNCTION__, ERROR_CREATE_FAILED); } else SetLastError(SE_CONNECT_SERVER, __FUNCTION__, ::WSAGetLastError()); } else SetLastError(SE_SOCKET_PREPARE, __FUNCTION__, ERROR_CANCELLED); } else SetLastError(SE_SOCKET_BIND, __FUNCTION__, ::WSAGetLastError()); } else SetLastError(SE_SOCKET_CREATE, __FUNCTION__, ::WSAGetLastError()); if(!isOK) { DWORD dwCode = ::GetLastError(); m_ccContext.Reset(FALSE); Stop(); ::SetLastError(dwCode); } return isOK; }
void XTcpClientImpl::DoConnect() { m_nState = CONNECTTING; m_asynSock.reset(CreateClientSocket(m_svrSockAddr.ipaddr().family())); InitSocketSignals(); bool ret = ConnectControlSocket(); if (!ret) { #ifdef WEBRTC_ANDROID LOGI("XTcpClientImpl::DoConnect false, try to reconnect after 3s...\n"); #else LOG(WARNING) << "XTcpClientImpl::DoConnect false, try to reconnect after 3s..."; #endif m_rCallback.OnServerConnectionFailure(); CurThread()->PostDelayed(kTryReconnectDelay, this, 1001); } }
BOOL CTcpClient::Start(LPCTSTR lpszRemoteAddress, USHORT usPort, BOOL bAsyncConnect, LPCTSTR lpszBindAddress, USHORT usLocalPort) { if(!CheckParams() || !CheckStarting()) return FALSE; PrepareStart(); m_ccContext.Reset(); BOOL isOK = FALSE; HP_SOCKADDR addrRemote, addrBind; if(CreateClientSocket(lpszRemoteAddress, addrRemote, usPort, lpszBindAddress, addrBind)) { if(BindClientSocket(addrBind, addrRemote, usLocalPort)) { if(TRIGGER(FirePrepareConnect(m_soClient)) != HR_ERROR) { if(ConnectToServer(addrRemote, bAsyncConnect)) { if(CreateWorkerThread()) isOK = TRUE; else SetLastError(SE_WORKER_THREAD_CREATE, __FUNCTION__, ERROR_CREATE_FAILED); } else SetLastError(SE_CONNECT_SERVER, __FUNCTION__, ::WSAGetLastError()); } else SetLastError(SE_SOCKET_PREPARE, __FUNCTION__, ENSURE_ERROR_CANCELLED); } else SetLastError(SE_SOCKET_BIND, __FUNCTION__, ::WSAGetLastError()); } else SetLastError(SE_SOCKET_CREATE, __FUNCTION__, ::WSAGetLastError()); if(!isOK) { m_ccContext.Reset(FALSE); EXECUTE_RESTORE_ERROR(Stop()); } return isOK; }
BOOL CTcpAgent::Connect(LPCTSTR pszRemoteAddress, USHORT usPort, CONNID* pdwConnID) { ASSERT(HasStarted() && pszRemoteAddress && usPort != 0); if(pdwConnID) *pdwConnID = 0; DWORD result = NO_ERROR; SOCKET soClient = INVALID_SOCKET; if(!HasStarted()) result = ERROR_INVALID_STATE; else { result = CreateClientSocket(soClient); if(result == NO_ERROR) { CONNID dwConnID = ::GenerateConnectionID(); if(pdwConnID) *pdwConnID = dwConnID; if(FirePrepareConnect(dwConnID, soClient) != HR_ERROR) result = ConnectToServer(dwConnID, soClient, pszRemoteAddress, usPort); else result = ERROR_FUNCTION_FAILED; } } if(result != NO_ERROR) { if(soClient != INVALID_SOCKET) ::ManualCloseSocket(soClient); ::SetLastError(result); } return (result == NO_ERROR); }
/* This function is the entry point for this program. Based on the command-line arguments, it invokes the suitable functions. */ int _cdecl main(int argc, char *argv[]) { // holds the return value from this function. // 0 indicates success, non-zero indicates failure. int retVal; int i; BOOL bStartupSuccessful = FALSE; WSADATA wsaData; printf("Entering main()\n"); // parse and validate the given arguments and determine if we should // continue the execution or return error. if (ParseArguments(argc, argv) == FALSE) { // error input. return a non-zero error code. retVal = 1; goto CLEANUP; } // call WSAStartup to initialize Winsock before calling any of its APIs. retVal = WSAStartup(MAKEWORD(2,2), &wsaData); if (retVal != 0) { printf("WSAStartup failed. Error = %d\n", retVal); goto CLEANUP; } // remember that the WSAStartup was successful so as to call WSACleanup // once, correspondingly. bStartupSuccessful = TRUE; for(i = 1; i <= g_ClientContext.loopCount; i++) { printf("\n\nPerforming Iteration : %d\n" "-------------------------\n",i); // create a socket that's connected to the server. g_ClientContext.sock = CreateClientSocket(); if (g_ClientContext.sock == INVALID_SOCKET) goto CLEANUP; // allocate and initialize the buffer to be sent. if (PrepareSendBuffer() == FALSE) goto CLOSE_SOCKET; // allocate and initialize a buffer for receiving. if (PrepareRecvBuffer() == FALSE) goto CLOSE_SOCKET; // perform the sends/recv according to the requested scenario. switch(g_ClientContext.scenario) { case SC_SEND_THEN_RECV : DoSendThenRecv(); break; case SC_SEND_NO_RECV : DoSendNoRecv(); break; case SC_SEND_WAIT_RECV : DoSendWaitRecv(); break; case SC_WAIT_SEND_RECV : DoWaitSendRecv(); break; case SC_IDEAL_SEND_RECV: DoIdealSendRecv(); break; default: printf("Unrecognized scenario\n"); break; } CLOSE_SOCKET: // free the send and recv buffers. FreeSendBuffer(); FreeRecvBuffer(); // close the client socket. closesocket(g_ClientContext.sock); printf("Closed socket %d. " "Total Bytes Recd = %d, " "Total Bytes Sent = %d\n", g_ClientContext.sock, g_ClientContext.nBytesRecd, g_ClientContext.sendBufSize - g_ClientContext.nBytesRemainingToBeSent); } CLEANUP: // call WSACleanup only if WSAStartup was successful. if (bStartupSuccessful) { // Inform Winsock that we are done with all the APIs. WSACleanup(); } printf("Exiting main()\n"); return retVal; }
Tcl_Channel Tcl_OpenTcpClient( Tcl_Interp *interp, /* For error reporting; can be NULL. */ int port, /* Port number to open. */ const char *host, /* Host on which to open port. */ const char *myaddr, /* Client-side address */ int myport, /* Client-side port */ int async) /* If nonzero, attempt to do an asynchronous * connect. Otherwise we do a blocking * connect. */ { TcpState *state; const char *errorMsg = NULL; void *addrlist = NULL, *myaddrlist = NULL; char channelName[SOCK_CHAN_LENGTH]; /* * Do the name lookups for the local and remote addresses. */ if (!TclCreateSocketAddress(interp, &addrlist, host, port, 0, &errorMsg) || !TclCreateSocketAddress(interp, &myaddrlist, myaddr, myport, 1, &errorMsg)) { if (addrlist != NULL) { freeaddrinfo(addrlist); } if (interp != NULL) { Tcl_SetObjResult(interp, Tcl_ObjPrintf( "couldn't open socket: %s", errorMsg)); } return NULL; } /* * Allocate a new TcpState for this socket. */ state = ckalloc(sizeof(TcpState)); memset(state, 0, sizeof(TcpState)); state->flags = async ? TCP_ASYNC_CONNECT : 0; state->cachedBlocking = TCL_MODE_BLOCKING; state->addrlist = addrlist; state->myaddrlist = myaddrlist; state->fds.fd = -1; /* * Create a new client socket and wrap it in a channel. */ if (CreateClientSocket(interp, state) != TCL_OK) { TcpCloseProc(state, NULL); return NULL; } sprintf(channelName, SOCK_TEMPLATE, (long) state); state->channel = Tcl_CreateChannel(&tcpChannelType, channelName, state, (TCL_READABLE | TCL_WRITABLE)); if (Tcl_SetChannelOption(interp, state->channel, "-translation", "auto crlf") == TCL_ERROR) { Tcl_Close(NULL, state->channel); return NULL; } return state->channel; }