这篇教程C++ CloseSocket函数代码示例写得很实用,希望能帮到您。
本文整理汇总了C++中CloseSocket函数的典型用法代码示例。如果您正苦于以下问题:C++ CloseSocket函数的具体用法?C++ CloseSocket怎么用?C++ CloseSocket使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。 在下文中一共展示了CloseSocket函数的27个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的C++代码示例。 示例1: WndProcLRESULT CALLBACK WndProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam) { int wmId, wmEvent; LPMINMAXINFO minInfo; static SOCKET serverSocket; static SOCKET clientSocket; switch (message) { case WM_CREATE: serverSocket = CreateSocket(hWnd); connectionStatus = statusNotConnected; EnableMenuItem(GetMenu(hWnd), IDM_DISCONNECT, MF_BYCOMMAND | MF_GRAYED); ListAddresses(); break; case WM_NETWORK: switch (WSAGETSELECTEVENT(lParam)) { case FD_ACCEPT: clientSocket = AcceptSocket(hWnd, serverSocket); break; case FD_CLOSE: if (connectionStatus == statusConnected) CloseSocket(hWnd, clientSocket); break; } break; case WM_COMMAND: wmId = LOWORD(wParam); wmEvent = HIWORD(wParam); switch (wmId) { case IDM_ABOUT: DialogBox(hInst, MAKEINTRESOURCE(IDD_ABOUTBOX), hWnd, About); break; case IDM_EXIT: Shell_NotifyIcon(NIM_DELETE, &trayIcon[trayIconNotConnected]); DestroyWindow(hWnd); break; case IDM_TRAY: HideInTray(hWnd, TRUE); break; case IDM_DISCONNECT: if (connectionStatus == statusConnected) CloseSocket(hWnd, clientSocket); break; case IDM_OPEN: HideInTray(hWnd, FALSE); break; default: return DefWindowProc(hWnd, message, wParam, lParam); } break; case WM_GETMINMAXINFO: minInfo = (LPMINMAXINFO)lParam; minInfo->ptMinTrackSize.x = kWidthMin; minInfo->ptMinTrackSize.y = kHeightMin; break; case WM_PAINT: DisplayWindow(hWnd); break; case WM_SYSCOMMAND: if (wParam == SC_MINIMIZE) HideInTray(hWnd, TRUE); else return DefWindowProc(hWnd, message, wParam, lParam); break; case WM_CLOSE: HideInTray(hWnd, TRUE); break; case WM_DESTROY: PostQuitMessage(0); break; case WM_TRAYMENU: if (wParam == kTrayId) { switch (lParam) { case WM_RBUTTONDOWN: DisplayTrayMenu(hWnd); break; case WM_LBUTTONDBLCLK: HideInTray(hWnd, !bInTray); break; default: break; } } break; default: return DefWindowProc(hWnd, message, wParam, lParam); } return 0;}
开发者ID:ikawamoto,项目名称:iphone-remotepad,代码行数:88,
示例2: connect_server/** void connect_server() * Attempts to connect to all configured servers. */int connect_server(int initial_id){ int attempts = 2; int rc = initial_id; /* Checking if the initial is zero, meaning we have to rotate to the * beginning. */ if(agt->rip[initial_id] == NULL) { rc = 0; initial_id = 0; } /* Closing socket if available. */ if(agt->sock >= 0) { sleep(1); CloseSocket(agt->sock); agt->sock = -1; if(agt->rip[1]) { verbose("%s: INFO: Closing connection to server (%s:%d).", ARGV0, agt->rip[rc], agt->port); } } while(agt->rip[rc]) { char *tmp_str; /* Checking if we have a hostname. */ tmp_str = strchr(agt->rip[rc], '/'); if(tmp_str) { char *f_ip; *tmp_str = '/0'; f_ip = OS_GetHost(agt->rip[rc], 5); if(f_ip) { char ip_str[128]; ip_str[127] = '/0'; snprintf(ip_str, 127, "%s/%s", agt->rip[rc], f_ip); free(f_ip); free(agt->rip[rc]); os_strdup(ip_str, agt->rip[rc]); tmp_str = strchr(agt->rip[rc], '/'); tmp_str++; } else { merror("%s: WARN: Unable to get hostname for '%s'.", ARGV0, agt->rip[rc]); *tmp_str = '/'; tmp_str++; } } else { tmp_str = agt->rip[rc]; } verbose("%s: INFO: Trying to connect to server (%s:%d).", ARGV0, agt->rip[rc], agt->port); /* IPv6 address: */ if(strchr(tmp_str,':') != NULL) { verbose("%s: INFO: Using IPv6 for: %s .", ARGV0, tmp_str); agt->sock = OS_ConnectUDP(agt->port, tmp_str, 1); } else { verbose("%s: INFO: Using IPv4 for: %s .", ARGV0, tmp_str); agt->sock = OS_ConnectUDP(agt->port, tmp_str, 0); } if(agt->sock < 0) { agt->sock = -1; merror(CONNS_ERROR, ARGV0, tmp_str); rc++; if(agt->rip[rc] == NULL)//.........这里部分代码省略.........
开发者ID:Ar0xA,项目名称:ossec-hids,代码行数:101,
示例3: CloseSocketvoid XLCDproc::Stop(){ CloseSocket(); m_bStop = true;}
开发者ID:Alxandr,项目名称:spotyxbmc2,代码行数:5,
示例4: server_test//.........这里部分代码省略......... defaultCipherList = "PSK-NULL-SHA256"; #else defaultCipherList = "PSK-AES128-CBC-SHA256"; #endif if (SSL_CTX_set_cipher_list(ctx, defaultCipherList) != SSL_SUCCESS) err_sys("server can't set cipher list 2"); }#endif }#if !defined(NO_FILESYSTEM) && !defined(NO_CERTS) /* if not using PSK, verify peer with certs */ if (doCliCertCheck && usePsk == 0) { SSL_CTX_set_verify(ctx, SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT,0); if (SSL_CTX_load_verify_locations(ctx, verifyCert, 0) != SSL_SUCCESS) err_sys("can't load ca file, Please run from CyaSSL home dir"); }#endif#ifdef OPENSSL_EXTRA SSL_CTX_set_default_passwd_cb(ctx, PasswordCallBack);#endif#if defined(CYASSL_SNIFFER) && !defined(HAVE_NTRU) && !defined(HAVE_ECC) /* don't use EDH, can't sniff tmp keys */ if (cipherList == NULL) { if (SSL_CTX_set_cipher_list(ctx, "AES256-SHA256") != SSL_SUCCESS) err_sys("server can't set cipher list 3"); }#endif ssl = SSL_new(ctx); if (ssl == NULL) err_sys("unable to get SSL");#ifdef HAVE_CRL CyaSSL_EnableCRL(ssl, 0); CyaSSL_LoadCRL(ssl, crlPemDir, SSL_FILETYPE_PEM, CYASSL_CRL_MONITOR | CYASSL_CRL_START_MON); CyaSSL_SetCRL_Cb(ssl, CRL_CallBack);#endif tcp_accept(&sockfd, &clientfd, (func_args*)args, port, useAnyAddr, doDTLS); if (!doDTLS) CloseSocket(sockfd); SSL_set_fd(ssl, clientfd); if (usePsk == 0) { #if !defined(NO_FILESYSTEM) && defined(OPENSSL_EXTRA) CyaSSL_SetTmpDH_file(ssl, dhParam, SSL_FILETYPE_PEM); #elif !defined(NO_CERTS) SetDH(ssl); /* repick suites with DHE, higher priority than PSK */ #endif }#ifndef CYASSL_CALLBACKS if (nonBlocking) { CyaSSL_set_using_nonblock(ssl, 1); tcp_set_nonblocking(&clientfd); NonBlockingSSL_Accept(ssl); } else if (SSL_accept(ssl) != SSL_SUCCESS) { int err = SSL_get_error(ssl, 0); char buffer[80]; printf("error = %d, %s/n", err, ERR_error_string(err, buffer)); err_sys("SSL_accept failed"); }#else NonBlockingSSL_Accept(ssl);#endif showPeer(ssl); idx = SSL_read(ssl, input, sizeof(input)-1); if (idx > 0) { input[idx] = 0; printf("Client message: %s/n", input); } else if (idx < 0) { int readErr = SSL_get_error(ssl, 0); if (readErr != SSL_ERROR_WANT_READ) err_sys("SSL_read failed"); } if (SSL_write(ssl, msg, sizeof(msg)) != sizeof(msg)) err_sys("SSL_write failed"); SSL_shutdown(ssl); SSL_free(ssl); SSL_CTX_free(ctx); CloseSocket(clientfd); ((func_args*)args)->return_code = 0;#ifdef USE_CYASSL_MEMORY if (trackMemory) ShowMemoryTracker();#endif /* USE_CYASSL_MEMORY */ return 0;}
开发者ID:pykoder,项目名称:cyassl,代码行数:101,
示例5: RecvFinishvoid RecvFinish(int32_t bytestransfer,struct connection *c,uint32_t err_code){ uint32_t recv_size; uint32_t free_buffer_size; buffer_t buf; uint32_t pos; int32_t i = 0; do{ if(bytestransfer == 0) return; else if(bytestransfer < 0 && err_code != EAGAIN){ //printf("recv close/n"); if(c->status != SCLOSE){ c->status = SCLOSE; CloseSocket(c->socket); //被动关闭 c->cb_disconnect(c,err_code); } return; }else if(bytestransfer > 0){ int32_t total_size = 0; do{ c->last_recv = GetSystemMs64(); update_next_recv_pos(c,bytestransfer); c->unpack_size += bytestransfer; total_size += bytestransfer; if(!unpack(c)) return; buf = c->next_recv_buf; pos = c->next_recv_pos; recv_size = BUFFER_SIZE; i = 0; do { free_buffer_size = buf->capacity - pos; free_buffer_size = recv_size > free_buffer_size ? free_buffer_size:recv_size; c->wrecvbuf[i].iov_len = free_buffer_size; c->wrecvbuf[i].iov_base = buf->buf + pos; recv_size -= free_buffer_size; pos += free_buffer_size; if(recv_size && pos >= buf->capacity) { pos = 0; if(!buf->next) buf->next = buffer_create_and_acquire(NULL,BUFFER_SIZE); buf = buf->next; } ++i; }while(recv_size); c->recv_overlap.m_super.iovec_count = i; c->recv_overlap.m_super.iovec = c->wrecvbuf; if(total_size >= BUFFER_SIZE) { Post_Recv(c->socket,&c->recv_overlap.m_super); return; } else bytestransfer = Recv(c->socket,&c->recv_overlap.m_super,&err_code); }while(bytestransfer > 0); } }while(1);}
开发者ID:cjl3080434008,项目名称:luanet,代码行数:61,
示例6: sd_listen_fdsvoid SocketManager::MainLoop() { // remove evironment values passed by systemd sd_listen_fds(1); // Daemon is ready to work. sd_notify(0, "READY=1"); m_working = true; while(m_working) { fd_set readSet = m_readSet; fd_set writeSet = m_writeSet; timeval localTempTimeout; timeval *ptrTimeout = &localTempTimeout; // I need to extract timeout from priority_queue. // Timeout in priority_queue may be deprecated. // I need to find some actual one. while(!m_timeoutQueue.empty()) { auto &top = m_timeoutQueue.top(); auto &desc = m_socketDescriptionVector[top.sock]; if (top.time == desc.timeout) { // This timeout matches timeout from socket. // It can be used. break; } else { // This socket was used after timeout in priority queue was set up. // We need to update timeout and find some useable one. Timeout tm = { desc.timeout , top.sock}; m_timeoutQueue.pop(); m_timeoutQueue.push(tm); } } if (m_timeoutQueue.empty()) { LogDebug("No usaable timeout found."); ptrTimeout = NULL; // select will wait without timeout } else { time_t currentTime = time(NULL); auto &pqTimeout = m_timeoutQueue.top(); // 0 means that select won't block and socket will be closed ;-) ptrTimeout->tv_sec = currentTime < pqTimeout.time ? pqTimeout.time - currentTime : 0; ptrTimeout->tv_usec = 0;// LogDebug("Set up timeout: " << (int)ptrTimeout->tv_sec// << " seconds. Socket: " << pqTimeout.sock); } int ret = select(m_maxDesc+1, &readSet, &writeSet, NULL, ptrTimeout); if (0 == ret) { // timeout Assert(!m_timeoutQueue.empty()); Timeout pqTimeout = m_timeoutQueue.top(); m_timeoutQueue.pop(); auto &desc = m_socketDescriptionVector[pqTimeout.sock]; if (!desc.isTimeout || !desc.isOpen) { // Connection was closed. Timeout is useless... desc.isTimeout = false; continue; } if (pqTimeout.time < desc.timeout) { // Is it possible? // This socket was used after timeout. We need to update timeout. pqTimeout.time = desc.timeout; m_timeoutQueue.push(pqTimeout); continue; } // timeout from m_timeoutQueue matches with socket.timeout // and connection is open. Time to close it! // Putting new timeout in queue here is pointless. desc.isTimeout = false; CloseSocket(pqTimeout.sock); // All done. Now we should process next select ;-) continue; } if (-1 == ret) { switch(errno) { case EINTR: LogDebug("EINTR in select"); break; default: int err = errno; LogError("Error in select: " << strerror(err)); return; } continue; } for(int i = 0; i<m_maxDesc+1 && ret; ++i) { if (FD_ISSET(i, &readSet)) { ReadyForRead(i); --ret;//.........这里部分代码省略.........
开发者ID:linearregression,项目名称:security-manager,代码行数:101,
示例7: Sys_Net_DeleteSocketvoid Sys_Net_DeleteSocket(struct SysNetData *netdata, struct SysSocket *socket){ CloseSocket(socket->s); FreeVec(socket);}
开发者ID:classicQ,项目名称:classicQ.github.io,代码行数:5,
示例8: client_test//.........这里部分代码省略......... if (CyaSSL_CTX_use_certificate_file(ctx, ourCert, SSL_FILETYPE_PEM) != SSL_SUCCESS) err_sys("can't load client cert file, check file and run from" " CyaSSL home dir"); if (CyaSSL_CTX_use_PrivateKey_file(ctx, ourKey, SSL_FILETYPE_PEM) != SSL_SUCCESS) err_sys("can't load client cert file, check file and run from" " CyaSSL home dir"); if (CyaSSL_CTX_load_verify_locations(ctx, verifyCert, 0) != SSL_SUCCESS) err_sys("can't load ca file, Please run from CyaSSL home dir"); if (doPeerCheck == 0) CyaSSL_CTX_set_verify(ctx, SSL_VERIFY_NONE, 0); if (benchmark) { /* time passed in number of connects give average */ int times = benchmark; int i = 0; double start = current_time(), avg; for (i = 0; i < times; i++) { tcp_connect(&sockfd, host, port, doDTLS); ssl = CyaSSL_new(ctx); CyaSSL_set_fd(ssl, sockfd); if (CyaSSL_connect(ssl) != SSL_SUCCESS) err_sys("SSL_connect failed"); CyaSSL_shutdown(ssl); CyaSSL_free(ssl); CloseSocket(sockfd); } avg = current_time() - start; avg /= times; avg *= 1000; /* milliseconds */ printf("CyaSSL_connect avg took: %8.3f milliseconds/n", avg); CyaSSL_CTX_free(ctx); ((func_args*)args)->return_code = 0; exit(EXIT_SUCCESS); } tcp_connect(&sockfd, host, port, doDTLS); ssl = CyaSSL_new(ctx); if (ssl == NULL) err_sys("unable to get SSL object"); CyaSSL_set_fd(ssl, sockfd);#ifdef HAVE_CRL if (CyaSSL_EnableCRL(ssl, CYASSL_CRL_CHECKALL) != SSL_SUCCESS) err_sys("can't enable crl check"); if (CyaSSL_LoadCRL(ssl, crlPemDir, SSL_FILETYPE_PEM, 0) != SSL_SUCCESS) err_sys("can't load crl, check crlfile and date validity"); if (CyaSSL_SetCRL_Cb(ssl, CRL_CallBack) != SSL_SUCCESS) err_sys("can't set crl callback");#endif if (matchName && doPeerCheck) CyaSSL_check_domain_name(ssl, domain);#ifdef NON_BLOCKING tcp_set_nonblocking(&sockfd); NonBlockingSSL_Connect(ssl);#else #ifndef CYASSL_CALLBACKS
开发者ID:lepidum,项目名称:cyassl,代码行数:67,
示例9: testserverint testserver(void) { unsigned int sockaddr; unsigned char mysocket; unsigned int rsize; mysocket = 0; // magic number! declare the socket number we will use (0-3) sockaddr = 0x400;//W5100_SKT_BASE(mysocket); // calc address of W5100 register set for this socket /* * The main loop. Control stays in this loop forever, processing any received packets * and sending any requested data. */ while (1) { LATAbits.LATA0 ^= 1; int x = w5100_read(sockaddr + W5100_SR_OFFSET); switch (x) // based on current status of socket... { case W5100_SKT_SR_CLOSED: // if socket is closed... LATBbits.LATB8 = 0; if (OpenSocket(mysocket, W5100_SKT_MR_TCP, HTTP_PORT) == mysocket) // if successful opening a socket... { Listen(mysocket); __delay_ms(1); } break; case W5100_SKT_SR_ESTABLISHED: // if socket connection is established... LATBbits.LATB8 = 1; rsize = ReceivedSize(mysocket); // find out how many bytes if (rsize > 0) { if (Receive(mysocket, buf, rsize) != W5100_OK) break; // if we had problems, all done /* * Add code here to process the payload from the packet. * * For now, we just ignore the payload and send a canned HTML page so the client at least * knows we are alive. */ strcpy((char *) buf, "HTTP/1.0 200 OK/r/nContent-Type: text/html/r/nPragma: no-cache/r/n/r/n"); strcat((char *) buf, "<html>/r/n<body>/r/n"); strcat((char *) buf, "<title>Phil's W5100 web server (ATmega644p)</title>/r/n"); strcat((char *) buf, "<h2>Phil's ATmega644p web server using Wiznet W5100 chip</h2>/r/n"); strcat((char *) buf, "<br /><hr>/r/n"); if (Send(mysocket, buf, strlen((char *) buf)) == W5100_FAIL) break; // just throw out the packet for now strcpy((char *) buf, "This is part 2 of the page."); strcat((char *) buf, "</body>/r/n</html>/r/n"); if (Send(mysocket, buf, strlen((char *) buf)) == W5100_FAIL) break; // just throw out the packet for now DisconnectSocket(mysocket); } else // no data yet... { __delay_us(10); } break; case W5100_SKT_SR_FIN_WAIT: case W5100_SKT_SR_CLOSING: case W5100_SKT_SR_TIME_WAIT: case W5100_SKT_SR_CLOSE_WAIT: case W5100_SKT_SR_LAST_ACK: CloseSocket(mysocket); break; } } return 0;}
开发者ID:thayerfox,项目名称:PicFlipVfd,代码行数:67,
示例10: socketint network::start(){ int count = 0; for (int i=0; i<3; i++) { SOCKET sock = socket(AF_INETX, SOCK_STREAM, IPPROTO_TCP); if (sock == INVALID_SOCKET) {#ifdef WIN32 DEBUG("%s (%i) :: Could not create socket (%d)/n", __FILE__, __LINE__, WSAGetLastError());#else DEBUG("%s (%i) :: Could not create socket (%d)/n", __FILE__, __LINE__, errno);#endif continue; } struct sockaddr_in sa; sa.sin_family = AF_INET; ushort port = 0; switch (i) { case 2 : port = Sharun->Settings.Net.Ports.Bridge; break; case 1 : port = Sharun->Settings.Net.Ports.Httpd; if (port == Sharun->Settings.Net.Ports.Game) port = 0; break; default : port = Sharun->Settings.Net.Ports.Game; } if (!port) { CloseSocket(&sock); continue; } sa.sin_port = htons(port); if (Sharun->Settings.Net.localhost) sa.sin_addr.s_addr = inet_addr("127.0.0.1"); else sa.sin_addr.s_addr = INADDR_ANY; int sockopt = 1; setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, (char*)&sockopt, sizeof(int)); if (bind(sock, (SOCKADDR *)&sa, sizeof(sa)) == SOCKET_ERROR) {#ifdef WIN32 DEBUG("%s (%i) :: Could not bind socket (%i - %d)/n", __FILE__, __LINE__, port, WSAGetLastError());#else DEBUG("%s (%i) :: Could not bind socket (%i - %d)/n", __FILE__, __LINE__, port, errno);#endif CloseSocket(&sock); continue; } if (listen(sock, 100) == SOCKET_ERROR) {#ifdef WIN32 DEBUG("%s (%i) :: Could not listen socket (%i - %d)/n", __FILE__, __LINE__, port, WSAGetLastError());#else DEBUG("%s (%i) :: Could not listen socket (%i - %d)/n", __FILE__, __LINE__, port, errno);#endif CloseSocket(&sock); continue; } count++; new connexion_list(sock, (port_type)i); DEBUG("%s (%i) :: Network Started (%s : %i)./n", __FILE__, __LINE__, Sharun->Settings.Net.localhost ? "localhost" : "ANY", port); } for (int i=0; count && Sharun->Settings.Thread.Httpd > 1 && i < Sharun->Settings.Thread.Httpd; i++) { thread_list *thread = new thread_list(); if (!thread->start((void*)HttpD_Thread, thread)) DEBUG("%s (%i) :: Could not start Httpd thread %i !/n", __FILE__, __LINE__, i); else DEBUG("%s (%i) :: Httpd thread %i started./n", __FILE__, __LINE__, i); } return count;}
开发者ID:GoneUp,项目名称:Sharun-Dream-s,代码行数:75,
示例11: memsetvoid UrRealtimeCommunication::run() { uint8_t buf[2048]; int bytes_read; memset(buf, 0, 2048); struct timeval timeout; fd_set readfds; FD_ZERO(&readfds); FD_SET(sockfd_, &readfds); print_debug("Realtime port: Got connection"); connected_ = true; while (keepalive_) { while (connected_ && keepalive_) { timeout.tv_sec = 0; //do this each loop as selects modifies timeout timeout.tv_usec = 500000; // timeout of 0.5 sec select(sockfd_ + 1, &readfds, NULL, NULL, &timeout); bytes_read = recv(sockfd_, (char*) buf, 2048, 0); if (bytes_read > 0) { setsockopt(sockfd_, IPPROTO_TCP, TCP_NODELAY, (char *) &flag_, sizeof(int)); robot_state_->unpack(buf); if (safety_count_ == safety_count_max_) { setSpeed(0., 0., 0., 0., 0., 0.); } safety_count_ += 1; } else { connected_ = false; CloseSocket(sockfd_); } } if (keepalive_) { //reconnect ofLog()<<"Realtime port: No connection. Is controller crashed? Will try to reconnect in 10 seconds..."<<endl; sockfd_ = socket(AF_INET, SOCK_STREAM, 0); if (sockfd_ < 0) { print_fatal("ERROR opening socket"); } flag_ = 1; setsockopt(sockfd_, IPPROTO_TCP, TCP_NODELAY, (char *) &flag_, sizeof(int)); setsockopt(sockfd_, IPPROTO_TCP, TCP_NODELAY, (char *) &flag_, sizeof(int)); setsockopt(sockfd_, SOL_SOCKET, SO_REUSEADDR, (char *) &flag_, sizeof(int)); SetNonBlocking(sockfd_, true); while (keepalive_ && !connected_) { std::this_thread::sleep_for(std::chrono::seconds(10)); fd_set writefds; connect(sockfd_, (struct sockaddr *) &serv_addr_, sizeof(serv_addr_)); FD_ZERO(&writefds); FD_SET(sockfd_, &writefds); select(sockfd_ + 1, NULL, &writefds, NULL, NULL); int flag_len; getsockopt(sockfd_, SOL_SOCKET, SO_ERROR, (char*)&flag_, &flag_len); if (flag_ < 0) { print_error("Error re-connecting to RT port 30003. Is controller started? Will try to reconnect in 10 seconds..."); } else { connected_ = true; print_info("Realtime port: Reconnected"); } } } } setSpeed(0., 0., 0., 0., 0., 0.); CloseSocket(sockfd_);}
开发者ID:pilzinho,项目名称:ofxURDriver,代码行数:67,
示例12: OnDoorRequestint OnDoorRequest(char *host_name, int host_port, char *pData, int nDataSize){ /* SOCKADDR_IN saServer; LPHOSTENT lphostent; WSADATA wsadata; SOCKET hsocket; */ char ipaddr[16]; int rsocket = -1; struct sockaddr_in daddr; struct timeval TimeOut; int nFlag; int nRet; memset( ipaddr, 0x00, 16 );#if 1 //nRet = GetDnsIp( host_name, ipaddr ); //Textout("Server = [%s], IPADDR = [%s]", host_name, ipaddr); //ipaddr[0] = 0;#else strcpy(ipaddr, "183.232.25.234");#endif if(jpush_address[0] != 0){ strcpy(ipaddr, jpush_address); } else { strcpy(ipaddr, "183.232.25.234"); } Textout("jpush ipaddr:%s",ipaddr); rsocket = InitSocket( 0, 1, NULL ); //tcp nFlag = 1; setsockopt( rsocket, IPPROTO_TCP, TCP_NODELAY, ( void* )&nFlag, sizeof( int ) ); TimeOut.tv_sec = 30; TimeOut.tv_usec = 0; setsockopt( rsocket, SOL_SOCKET, SO_RCVTIMEO, ( char* )&TimeOut, sizeof( TimeOut ) ); TimeOut.tv_sec = 30; TimeOut.tv_usec = 0; setsockopt( rsocket, SOL_SOCKET, SO_SNDTIMEO, ( char* )&TimeOut, sizeof( TimeOut ) ); bzero( &daddr, sizeof( struct sockaddr_in ) ); daddr.sin_family = AF_INET; daddr.sin_port = htons(host_port); daddr.sin_addr.s_addr = inet_addr( ipaddr ); nRet = connect( rsocket, ( struct sockaddr* )&daddr, sizeof( struct sockaddr ) ); if(nRet == -1) //SOCKET_ERROR) { Textout( "Can't connect %s",host_name); CloseSocket( rsocket ); return -1; } else { Textout("connected with host %s",host_name); } nRet = send(rsocket, pData, nDataSize, 0); if(nRet == -1) //SOCKET_ERROR) { Textout( "Can't Send"); CloseSocket( rsocket ); return -1; } else { Textout("send() OK"); //Textout("pData:%s",pData); } char dest[1024]; nRet=0; nRet=recv(rsocket,(char *)dest,sizeof(dest),0); if(nRet>0) { dest[nRet]=0; if(strstr(dest,"Succeed") == NULL ) { nRet = -1; Textout("Received bytes:%d",nRet); printf("Result:%s/n",dest); } else { printf("jPush send Succeed!/n"); nRet = 0;//.........这里部分代码省略.........
开发者ID:codywon,项目名称:bell-jpg,代码行数:101,
示例13: WSAStartupint WebRequest::Request( int request_type , std::string url_host , int url_port , std::string url_path , std::string data){ bool secure = false; mMessageHeader = ""; mMessageBody.clear(); // temp fix for POST recognition data = "_start_=1&" + data + "&_end_=1"; mReadSize = 1024; mError = 0; if(request_type == HTTPS_GET || request_type == HTTPS_POST || request_type == HTTPS_PUT || request_type == HTTPS_DELETE) { secure = true; } #ifdef WIN32 WSADATA wsa; // startup winsock mError = WSAStartup(MAKEWORD(2,0),&wsa); if(mError) { printf("Error in Startup = %d/n", mError); return -1; } #endif // socket int socket = 0; // struct for socket struct sockaddr_in host_addr = {0}; // information about host struct hostent *host = {0}; // request of client std::string request; // SSL context SSL_CTX *sslContext = NULL; // SSL socket SSL *sslSocket = NULL; // get IP from name host host = gethostbyname(url_host.c_str()); if (host == NULL) { printf("Unknown Host %s/n", url_host.c_str()); return -1; } // create socket TCP socket = ::socket(PF_INET, SOCK_STREAM, 0); if (socket < 0) { printf("Socket Error/n"); return -1; } // create host struct host_addr.sin_family = AF_INET; // set IP addres host_addr.sin_addr = *((struct in_addr *)host->h_addr); // set HTTP port host_addr.sin_port = htons(url_port); // connect mError = connect(socket, (struct sockaddr *)&host_addr, sizeof(host_addr)); if (mError == -1) { CloseSocket(socket); printf("Connection Error/n"); return -1; } if(secure) { // init OpenSSL SSL_load_error_strings(); SSL_library_init(); // create context sslContext = SSL_CTX_new(SSLv23_client_method());//.........这里部分代码省略.........
开发者ID:drawcode,项目名称:ddengine,代码行数:101,
示例14: memcpyvoid * ClientRecevier::run(void * arg){ if (NULL == arg) { return reinterpret_cast<void *>(-error::INVALIDSOCKARG); } SockClientRecviveParams * scr = (SockClientRecviveParams *)arg; /* Dump */ int sockfd = scr->sockfd(); ClientHandler * clientHandler = scr->clientHandler(); SockDidFinish fb; fb.fd = sockfd;/* Fill FI sockfd */ bool teminate = clientHandler->shouldTeminateRecv(sockfd); uint8_t * buf = new uint8_t[4096]; SockRecved rcv; rcv.fd = sockfd; memcpy(&(rcv.info), scr->from(), sizeof(NetProtocol)); int ret; while (0 == teminate) { memset(buf, 0, 4096); ret = RecvFromSockfd( sockfd, buf, 0, 4096, 15 * 1e6, 15 * 1e6); if ((ret < 0) && (ret > -1000)) { fb.code = ret;/* Fail */ ShutdownSocket(sockfd, shutdownhow::RDWR); CloseSocket(sockfd); clientHandler->didFinish(fb); goto end; } else if (0 == ret) { /* disconnected */ fb.code = 0; ShutdownSocket(sockfd, shutdownhow::RDWR); CloseSocket(sockfd); clientHandler->didFinish(fb); goto end; } else if (ret > 0) { /* success */ rcv.data = buf; rcv.count = ret; clientHandler->didReceive(rcv); } else { /* < -1000 timeout */ } teminate = clientHandler->shouldTeminateRecv(sockfd); } fb.code = 1;/* user terminate */ ShutdownSocket(sockfd, shutdownhow::RDWR); CloseSocket(sockfd); clientHandler->didFinish(fb);end: if (NULL != scr) { delete scr; scr = NULL; } if (NULL != buf) { delete[] buf; buf = NULL; } if (NULL != clientHandler) { if (NULL != clientHandler->gc()) { clientHandler->gc()->gc(clientHandler); } /* else has released */ clientHandler = NULL; } return (void *)0;/* success */}
开发者ID:iamyuiwong,项目名称:socket,代码行数:67,
示例15: CHROMIUM_LOGvoidNfcConsumer::OnConnectError(){ CHROMIUM_LOG("NFC: %s/n", __FUNCTION__); CloseSocket();}
开发者ID:chardis,项目名称:gecko-dev,代码行数:6,
示例16: return//.........这里部分代码省略......... /* timeout */ code = -ETIMEDOUT; if (0x00000001 == this->ver()) { goto retry_later; } else { goto select_to; } } else { /* final check sokcet error */ int errlen = sizeof(ret);# if !defined(WIN32) getsockopt(sockfd, SOL_SOCKET, SO_ERROR, &ret, (socklen_t *)&errlen);# else getsockopt(sockfd, SOL_SOCKET, SO_ERROR, reinterpret_cast<char *>(&ret), (socklen_t *)&errlen);# endif if (0 != ret) { /* connect fail */ errno = ret; code = -ret; snprintf(msg, 127, "FAIL: select: %s", strerror(ret)); msg[127] = '/0'; if (0x00000001 == this->ver()) { goto retry_later; } else { goto select_fail; } } } break;/* ok */retry_later: if (sockfd > 0) { CloseSocket(sockfd); sockfd = -1; } usleep(10 * 1e6); usleep(10 * 1e6); usleep(10 * 1e6); } while(true); /* Final ok */# if defined(__APPLE__) { int set = 1; setsockopt(sockfd, SOL_SOCKET, SO_NOSIGPIPE, (void *)&set, sizeof(int)); }# endif /* defined(__APPLE__) */ { rcvparams = new SockClientRecviveParams(sockfd, clientHandler, target); /* start on received thread */ ret = ClientHelper::startReceiveFromPeer(rcvparams); if (0 != ret) { OYWL_ERRSN("startReceiveFromPeer() fail", ret); code = ret; delete rcvparams; rcvparams = NULL; } else { /* success */ code = 0; } rcvparams = NULL; } /* Feedback */ conHandler.code = code; clientHandler->didConnect(conHandler); if (0 != code) { OYWL_SN0("Will delete clientHandler by code", code); delete clientHandler; clientHandler = NULL; } /* Final delete */ if (NULL != cps) { OYWL_S0("Will delete cps"); delete cps; cps = NULL; } return reinterpret_cast<void *>(0);/* Success */select_to:select_fail: if (NULL != clientHandler) { conHandler.code = code; clientHandler->didConnect(conHandler); OYWL_S0("Will delete clientHandler by not nil"); delete clientHandler; clientHandler = NULL; } if (NULL != rcvparams) { delete rcvparams; rcvparams = NULL; } /* Final delete */ if (NULL != cps) { OYWL_S0("Will delete cps"); delete cps; cps = NULL; } return (void *)-1;}
开发者ID:iamyuiwong,项目名称:socket,代码行数:101,
示例17: echoclient_test//.........这里部分代码省略......... int argc = 0; char** argv = 0; ((func_args*)args)->return_code = -1; /* error state */ argc = ((func_args*)args)->argc; argv = ((func_args*)args)->argv; if (argc >= 2) { fin = fopen(argv[1], "r"); inCreated = 1; } if (argc >= 3) { fout = fopen(argv[2], "w"); outCreated = 1; } if (!fin) err_sys("can't open input file"); if (!fout) err_sys("can't open output file"); tcp_connect(&sockfd, yasslIP, yasslPort);#if defined(CYASSL_DTLS) method = DTLSv1_client_method();#elif !defined(NO_TLS) method = TLSv1_client_method();#else method = SSLv3_client_method();#endif ctx = SSL_CTX_new(method);#ifndef NO_FILESYSTEM if (SSL_CTX_load_verify_locations(ctx, caCert, 0) != SSL_SUCCESS) err_sys("can't load ca file"); #ifdef HAVE_ECC if (SSL_CTX_load_verify_locations(ctx, eccCert, 0) != SSL_SUCCESS) err_sys("can't load ca file"); #endif#else load_buffer(ctx, caCert, CYASSL_CA);#endif#ifdef OPENSSL_EXTRA SSL_CTX_set_default_passwd_cb(ctx, PasswordCallBack);#endif ssl = SSL_new(ctx); SSL_set_fd(ssl, sockfd);#if defined(USE_WINDOWS_API) && defined(CYASSL_DTLS) && defined(NO_MAIN_DRIVER) /* let echoserver bind first, TODO: add Windows signal like pthreads does */ Sleep(100);#endif if (SSL_connect(ssl) != SSL_SUCCESS) err_sys("SSL_connect failed"); while (fgets(send, sizeof(send), fin)) { sendSz = (int)strlen(send) + 1; if (SSL_write(ssl, send, sendSz) != sendSz) err_sys("SSL_write failed"); if (strncmp(send, "quit", 4) == 0) { fputs("sending server shutdown command: quit!/n", fout); break; } if (strncmp(send, "break", 4) == 0) { fputs("sending server session close: break!/n", fout); break; } while (sendSz) { int got; if ( (got = SSL_read(ssl, reply, sizeof(reply))) > 0) { fputs(reply, fout); sendSz -= got; } else break; } }#ifdef CYASSL_DTLS strncpy(send, "break", 6); sendSz = (int)strlen(send); /* try to tell server done */ SSL_write(ssl, send, sendSz);#else SSL_shutdown(ssl);#endif SSL_free(ssl); SSL_CTX_free(ctx); fflush(fout); if (inCreated) fclose(fin); if (outCreated) fclose(fout); CloseSocket(sockfd); ((func_args*)args)->return_code = 0; }
开发者ID:AllardJ,项目名称:Tomato,代码行数:101,
示例18: ulockvoid SocketManager::ProcessQueue() { WriteBuffer buffer; WriteData data; { std::lock_guard<std::mutex> ulock(m_eventQueueMutex); while (!m_writeBufferQueue.empty()) { buffer = m_writeBufferQueue.front(); m_writeBufferQueue.pop(); auto &desc = m_socketDescriptionVector[buffer.connectionID.sock]; if (!desc.isOpen) { LogDebug("Received packet for write but connection is closed. Packet ignored!"); continue; } if (desc.counter != buffer.connectionID.counter) { LogDebug("Received packet for write but counter is broken. Packet ignored!"); continue; } if (desc.useSendMsg) { LogError("Some service tried to push rawdata to socket that usees sendmsg!"); continue; } std::copy( buffer.rawBuffer.begin(), buffer.rawBuffer.end(), std::back_inserter(desc.rawBuffer)); FD_SET(buffer.connectionID.sock, &m_writeSet); } while(!m_writeDataQueue.empty()) { data = m_writeDataQueue.front(); m_writeDataQueue.pop(); auto &desc = m_socketDescriptionVector[data.connectionID.sock]; if (!desc.isOpen) { LogDebug("Received packet for sendmsg but connection is closed. Packet ignored!"); continue; } if (desc.counter != data.connectionID.counter) { LogDebug("Received packet for write but counter is broken. Packet ignored!"); continue; } if (!desc.useSendMsg) { LogError("Some service tries to push SendMsgData to socket that uses write!"); continue; } desc.sendMsgDataQueue.push(data.sendMsgData); FD_SET(data.connectionID.sock, &m_writeSet); } } while (1) { ConnectionID connection; { std::lock_guard<std::mutex> ulock(m_eventQueueMutex); if (m_closeQueue.empty()) return; connection = m_closeQueue.front(); m_closeQueue.pop(); } if (!m_socketDescriptionVector[connection.sock].isOpen) continue; if (connection.counter != m_socketDescriptionVector[connection.sock].counter) continue; CloseSocket(connection.sock); }}
开发者ID:linearregression,项目名称:security-manager,代码行数:82,
示例19: EndSignalvoid EndSignal(int sig){ DB(fprintf(stderr,"EndSignal()/n")); CloseSocket(); exit(0);}
开发者ID:kouamano,项目名称:server-client_base,代码行数:5,
示例20: ASSERT//接收完成函数bool CServerSocketItem::OnRecvCompleted(COverLappedRecv * pOverLappedRecv, DWORD dwThancferred){ //效验数据 ASSERT(m_bRecvIng==true); //设置变量 m_bRecvIng=false; m_dwRecvTickCount=GetTickCount(); //判断关闭 if (m_hSocket==INVALID_SOCKET) { CloseSocket(m_wRountID); return true; } //接收数据 int iRetCode=recv(m_hSocket,(char *)m_cbRecvBuf+m_wRecvSize,sizeof(m_cbRecvBuf)-m_wRecvSize,0); if (iRetCode<=0) { CloseSocket(m_wRountID); return true; } //接收完成 m_wRecvSize+=iRetCode; BYTE cbBuffer[SOCKET_BUFFER]; CMD_Head * pHead=(CMD_Head *)m_cbRecvBuf; //处理数据 try { while (m_wRecvSize>=sizeof(CMD_Head)) { //效验数据 WORD wPacketSize=pHead->CmdInfo.wPacketSize; if (wPacketSize>SOCKET_BUFFER) throw TEXT("数据包超长"); if (wPacketSize<sizeof(CMD_Head)) throw TEXT("数据包非法"); if (pHead->CmdInfo.cbVersion!=SOCKET_VER) throw TEXT("数据包版本错误"); if (m_wRecvSize<wPacketSize) break; //提取数据 CopyMemory(cbBuffer,m_cbRecvBuf,wPacketSize); WORD wRealySize=CrevasseBuffer(cbBuffer,wPacketSize); ASSERT(wRealySize>=sizeof(CMD_Head)); m_dwRecvPacketCount++; //解释数据 WORD wDataSize=wRealySize-sizeof(CMD_Head); void * pDataBuffer=cbBuffer+sizeof(CMD_Head); CMD_Command Command=((CMD_Head *)cbBuffer)->CommandInfo; //内核命令 if (Command.wMainCmdID==MDM_KN_COMMAND) { switch (Command.wSubCmdID) { case SUB_KN_DETECT_SOCKET: //网络检测 { break; } default: throw TEXT("非法命令码"); } } else { //消息处理 m_pIServerSocketItemSink->OnSocketReadEvent(Command,pDataBuffer,wDataSize,this); } //删除缓存数据 m_wRecvSize-=wPacketSize; MoveMemory(m_cbRecvBuf,m_cbRecvBuf+wPacketSize,m_wRecvSize); } } catch (...) { CloseSocket(m_wRountID); return false; } return RecvData();}
开发者ID:firehot,项目名称:WH2008,代码行数:84,
示例21: peekvoid SampleSocketPort::pending(void){//cerr << "Pending called " << endl; if(!m_bOpen) return; // Read all available bytes into our buffer int nBytesAvail = peek(m_pBuf, MAX_RXBUF);//cerr << "Pending .. " << nBytesAvail << endl; if(!m_bReceptionStarted) { //Start the receive timer ResetReadTimeout(MAX_RXTIMEOUT); //Got 'n' seconds to get all the data else we timeout m_bReceptionStarted = true; } else { if(m_bTimedOut) //The receive timer has expired...this is a timeout condition { ResetReadTimeout(MAX_RXTIMEOUT); //Clear the timeout flag m_nLastBytesAvail = 0; //Reset the flags m_bReceptionStarted = false; OnRxTimeout(); //Do whatever 'we' do for a timeout (probably a flush or disconnect)... return; } } if(m_nLastBytesAvail == nBytesAvail) //Check if any more data has been received since last time { //No point in parsing unless this has changed! //Maybe yield in here! //Thread::yield(); if(nBytesAvail == 0) //If we have been called with 0 bytes available (twice now) { //a disconnection has occurred if(!m_bDoDisconnect) { CloseSocket(); //Force the close } } return; } //Depending on your application you may want to attempt to process the extra data //(or change your MAX_RXBUF). // //Here I just flush the whole lot, because I assume a 'legal' client wont send more than //we can receive....maybe someone is trying to flood / overrun us! if(nBytesAvail > MAX_RXBUF) { cerr << "TCP/IP overflow..." << endl; FlushRxData(); m_nLastBytesAvail = 0; m_bReceptionStarted = false; return; } m_nLastBytesAvail = nBytesAvail; //In this loop you may parse the received data to determine whether a whole //'packet' has arrived. What you do in here depends on what data you are sending. //Here we will just look for a /r/n terminator sequence. for(int i=0; i < nBytesAvail; i++) {/***************************SHOULD BE CUSTOMISED*******************/ if(m_pBuf[i] == '/r') { if(i+1 < nBytesAvail) { if(m_pBuf[i+1] == '/n') { //Terminator sequence found /**************************************************************/ // COMPULSORY ... Clear the flag and count.. // do this when you have received a good packet m_nLastBytesAvail = 0; m_bReceptionStarted = false; /**************************************************************/ // Now receive the data into a buffer and call our receive function int nLen = i+2; char *pszRxData = new char[nLen+1]; //Allow space for terminator receive(pszRxData, nLen); //Receive the data pszRxData[nLen] = '/0'; //Terminate it OnDataReceived(pszRxData, nLen); delete [] pszRxData; return; } } }/***************************END CUSTOMISATION*******************/ }}
开发者ID:SiteView,项目名称:ecc82Server,代码行数:93,
示例22: Loggerint Logger(LISTE *plcs){ int res=0,Comm_err=0,Read_Something=0; if (TEST) { ListePlc(plcs); //return(0); } int now=time(NULL); res=BuildSockets(plcs); while (!Terminated) { ELEMENT *elt=GetFirst(plcs); while (elt!=NULL) // PLCs { PLC *plc=elt->Data; /* Something to do ? */ if (plc->Next_Time>time(NULL)) { elt=GetNext(plcs,elt); continue; } /* Test Socket */ if (plc->socket<0) { if (BuildSocket(plc)<0) { Log(LOG_WARNING,"Socket unavailable for : %s/n",plc->PlcName); plc->Next_Time=now+WAIT_FOR_RECONNECT; elt=GetNext(plcs,elt); continue; } else Log(LOG_INFO,"Socket build for : %s/n",plc->PlcName); } now=time(NULL); Read_Something=0; Comm_err=1; //plc->Next_Time=now+0.95*MAX_SAMPLE/1000; plc->Next_Time=now+MAX_SAMPLE; Log(LOG_DEBUG,"Set plc->Next_Time in %d seconds (MAX_SAMPLE : %d)/n",plc->Next_Time-now,MAX_SAMPLE); /* Read Tags */ ELEMENT *elt2=GetFirst(&(plc->Tags)); while (elt2!=NULL) { TAG *tag=elt2->Data; if ((now-tag->Time_Value)>(1.5*tag->Time_Sample)) Log(LOG_WARNING,"Time Sample exceed on tag : %s (%s)/n",tag->TagName,plc->PlcName); if ((now-tag->Time_Value)>=tag->Time_Sample) { //Log(LOG_DEBUG,"Reading tag : %s (%s) (%d - %d > %d)/n",tag->TagName,plc->PlcName,now,tag->Time_Value,tag->Time_Sample); Read_Something=1; res=ReadTag(plc,tag); if (res==0) Comm_err=0; // At least one tag is Ok if (mb_errno==EPIPE) CloseSocket(plc->socket,plcs); } if ((tag->Time_Value+tag->Time_Sample)<(plc->Next_Time)) { plc->Next_Time=tag->Time_Value+tag->Time_Sample; Log(LOG_DEBUG,"plc->Next_Time in %d seconds*/n",plc->Next_Time-now); } elt2=GetNext(&(plc->Tags),elt2); } /* Read Packets */ elt2=GetFirst(&(plc->Packets)); while (elt2!=NULL) { PACKET *packet=elt2->Data; if ((now-packet->Time_Value)>(1.5*packet->Time_Sample)) Log(LOG_WARNING,"Time Sample exceed on packet : %s (%s)/n",packet->BaseAddress,plc->PlcName); if ((now-packet->Time_Value)>=packet->Time_Sample) { Read_Something=1; res=ReadPacket(plc,packet); if (res>=0) Comm_err=0; // At least one tag is Ok if (mb_errno==EPIPE) CloseSocket(plc->socket,plcs); } if ((packet->Time_Value+packet->Time_Sample)<(plc->Next_Time)) { plc->Next_Time=packet->Time_Value+packet->Time_Sample; Log(LOG_DEBUG,"plc->Next_Time in %d seconds/n",plc->Next_Time-now); } elt2=GetNext(&(plc->Packets),elt2); } /* Check Plc */ if (Comm_err && Read_Something) // All Tags & packets are in error { Log(LOG_WARNING,"All tags in error for : %s suspending for %d seconds/n",plc->PlcName,WAIT_FOR_RECONNECT); plc->Next_Time=now+WAIT_FOR_RECONNECT; } if (plc->Next_Time>0.8*(time(NULL)+MODBUS_SOCK_TIMEOUT)) { close(plc->socket); plc->socket=-1; Log(LOG_DEBUG,"Closing socket for plc : %s /n",plc->PlcName); } elt=GetNext(plcs,elt); } sleep(1); } Log(LOG_NOTICE,"Killing Connections/n"); KillAll(plcs);//.........这里部分代码省略.........
开发者ID:Felipeasg,项目名称:TuxPLC,代码行数:101,
示例23: echoserver_test//.........这里部分代码省略......... while (!shutDown) { CYASSL* ssl = 0; char command[SVR_COMMAND_SIZE+1]; int echoSz = 0; int clientfd; int firstRead = 1; int gotFirstG = 0; #ifndef CYASSL_DTLS SOCKADDR_IN_T client; socklen_t client_len = sizeof(client); clientfd = accept(sockfd, (struct sockaddr*)&client, (ACCEPT_THIRD_T)&client_len);#else clientfd = udp_read_connect(sockfd);#endif if (clientfd == -1) err_sys("tcp accept failed"); ssl = CyaSSL_new(ctx); if (ssl == NULL) err_sys("SSL_new failed"); CyaSSL_set_fd(ssl, clientfd); #ifdef __MORPHOS__ CyaSSL_set_socketbase(ssl, SocketBase); #endif #if !defined(NO_FILESYSTEM) && !defined(NO_DH) CyaSSL_SetTmpDH_file(ssl, dhParam, SSL_FILETYPE_PEM); #elif !defined(NO_DH) SetDH(ssl); /* will repick suites with DHE, higher than PSK */ #endif if (CyaSSL_accept(ssl) != SSL_SUCCESS) { printf("SSL_accept failed/n"); CyaSSL_free(ssl); CloseSocket(clientfd); continue; }#if defined(PEER_INFO) showPeer(ssl);#endif while ( (echoSz = CyaSSL_read(ssl, command, sizeof(command)-1)) > 0) { if (firstRead == 1) { firstRead = 0; /* browser may send 1 byte 'G' to start */ if (echoSz == 1 && command[0] == 'G') { gotFirstG = 1; continue; } } else if (gotFirstG == 1 && strncmp(command, "ET /", 4) == 0) { strncpy(command, "GET", 4); /* fall through to normal GET */ } if ( strncmp(command, "quit", 4) == 0) { printf("client sent quit command: shutting down!/n"); shutDown = 1; break; } if ( strncmp(command, "break", 5) == 0) { printf("client sent break command: closing session!/n"); break; }#ifdef SESSION_STATS if ( strncmp(command, "printstats", 10) == 0) { PrintSessionStats();
开发者ID:filip-maryjanski,项目名称:CyaSSL.library,代码行数:67,
示例24: client_test//.........这里部分代码省略.........#if !defined(NO_CERTS) if (!usePsk && doPeerCheck == 0) CyaSSL_CTX_set_verify(ctx, SSL_VERIFY_NONE, 0);#endif#ifdef HAVE_CAVIUM CyaSSL_CTX_UseCavium(ctx, CAVIUM_DEV_ID);#endif#ifdef HAVE_SNI if (sniHostName) if (CyaSSL_CTX_UseSNI(ctx, 0, sniHostName, XSTRLEN(sniHostName)) != SSL_SUCCESS) err_sys("UseSNI failed");#endif if (benchmark) { /* time passed in number of connects give average */ int times = benchmark; int i = 0; double start = current_time(), avg; for (i = 0; i < times; i++) { tcp_connect(&sockfd, host, port, doDTLS); ssl = CyaSSL_new(ctx); CyaSSL_set_fd(ssl, sockfd); if (CyaSSL_connect(ssl) != SSL_SUCCESS) err_sys("SSL_connect failed"); CyaSSL_shutdown(ssl); CyaSSL_free(ssl); CloseSocket(sockfd); } avg = current_time() - start; avg /= times; avg *= 1000; /* milliseconds */ printf("CyaSSL_connect avg took: %8.3f milliseconds/n", avg); CyaSSL_CTX_free(ctx); ((func_args*)args)->return_code = 0; exit(EXIT_SUCCESS); } #if defined(CYASSL_MDK_ARM) CyaSSL_CTX_set_verify(ctx, SSL_VERIFY_NONE, 0); #endif ssl = CyaSSL_new(ctx); if (ssl == NULL) err_sys("unable to get SSL object"); CyaSSL_set_quiet_shutdown(ssl, 1) ; if (doDTLS) { SOCKADDR_IN_T addr; build_addr(&addr, host, port, 1); CyaSSL_dtls_set_peer(ssl, &addr, sizeof(addr)); tcp_socket(&sockfd, 1); } else { tcp_connect(&sockfd, host, port, 0); } CyaSSL_set_fd(ssl, sockfd);
开发者ID:Coderz333,项目名称:cyassl,代码行数:67,
示例25: CloseSocketnsUDPSocket::~nsUDPSocket(){ CloseSocket(); MOZ_COUNT_DTOR(nsUDPSocket);}
开发者ID:emilio,项目名称:gecko-dev,代码行数:5,
示例26: echoclient_test//.........这里部分代码省略......... err_sys("can't load ca file, Please run from CyaSSL home dir"); #endif #ifdef HAVE_ECC if (SSL_CTX_load_verify_locations(ctx, eccCert, 0) != SSL_SUCCESS) err_sys("can't load ca file, Please run from CyaSSL home dir"); #endif#elif !defined(NO_CERTS) if (!doPSK) load_buffer(ctx, caCert, CYASSL_CA);#endif#if defined(CYASSL_SNIFFER) && !defined(HAVE_NTRU) && !defined(HAVE_ECC) /* don't use EDH, can't sniff tmp keys */ SSL_CTX_set_cipher_list(ctx, "AES256-SHA");#endif if (doPSK) {#ifndef NO_PSK const char *defaultCipherList; CyaSSL_CTX_set_psk_client_callback(ctx, my_psk_client_cb); #ifdef HAVE_NULL_CIPHER defaultCipherList = "PSK-NULL-SHA256"; #else defaultCipherList = "PSK-AES128-CBC-SHA256"; #endif if (CyaSSL_CTX_set_cipher_list(ctx,defaultCipherList) !=SSL_SUCCESS) err_sys("client can't set cipher list 2");#endif }#ifdef OPENSSL_EXTRA SSL_CTX_set_default_passwd_cb(ctx, PasswordCallBack);#endif ssl = SSL_new(ctx); if (doDTLS) { SOCKADDR_IN_T addr; build_addr(&addr, yasslIP, yasslPort); CyaSSL_dtls_set_peer(ssl, &addr, sizeof(addr)); tcp_socket(&sockfd, 1); } else { tcp_connect(&sockfd, yasslIP, yasslPort, 0); } SSL_set_fd(ssl, sockfd);#if defined(USE_WINDOWS_API) && defined(CYASSL_DTLS) && defined(NO_MAIN_DRIVER) /* let echoserver bind first, TODO: add Windows signal like pthreads does */ Sleep(100);#endif if (SSL_connect(ssl) != SSL_SUCCESS) err_sys("SSL_connect failed"); while (fgets(msg, sizeof(msg), fin)) { sendSz = (int)strlen(msg); if (SSL_write(ssl, msg, sendSz) != sendSz) err_sys("SSL_write failed"); if (strncmp(msg, "quit", 4) == 0) { fputs("sending server shutdown command: quit!/n", fout); break; } if (strncmp(msg, "break", 5) == 0) { fputs("sending server session close: break!/n", fout); break; } while (sendSz) { int got; if ( (got = SSL_read(ssl, reply, sizeof(reply)-1)) > 0) { reply[got] = 0; fputs(reply, fout); sendSz -= got; } else break; } }#ifdef CYASSL_DTLS strncpy(msg, "break", 6); sendSz = (int)strlen(msg); /* try to tell server done */ SSL_write(ssl, msg, sendSz);#else SSL_shutdown(ssl);#endif SSL_free(ssl); SSL_CTX_free(ctx); fflush(fout); if (inCreated) fclose(fin); if (outCreated) fclose(fout); CloseSocket(sockfd); ((func_args*)args)->return_code = 0; }
开发者ID:luckgogo,项目名称:cyassl,代码行数:101,
示例27: server_test//.........这里部分代码省略......... protocol_name, protocol_nameSz); else if (err == SSL_ALPN_NOT_FOUND) printf("No ALPN response sent (no match)/n"); else printf("Getting ALPN protocol name failed/n"); err = wolfSSL_ALPN_GetPeerProtocol(ssl, &list, &listSz); if (err == SSL_SUCCESS) printf("List of protocol names sent by Client: %s (%d)/n", list, listSz); else printf("Get list of client's protocol name failed/n"); free(list); }#endif if(echoData == 0 && throughput == 0) { ret = SSL_read(ssl, input, sizeof(input)-1); if (ret > 0) { input[ret] = 0; printf("Client message: %s/n", input); } else if (ret < 0) { int readErr = SSL_get_error(ssl, 0); if (readErr != SSL_ERROR_WANT_READ) err_sys("SSL_read failed"); } if (SSL_write(ssl, msg, sizeof(msg)) != sizeof(msg)) err_sys("SSL_write failed"); } else { ServerEchoData(ssl, clientfd, echoData, throughput); }#if defined(WOLFSSL_MDK_SHELL) && defined(HAVE_MDK_RTX) os_dly_wait(500) ;#elif defined (CYASSL_TIRTOS) Task_yield();#endif if (doDTLS == 0) { ret = SSL_shutdown(ssl); if (wc_shutdown && ret == SSL_SHUTDOWN_NOT_DONE) SSL_shutdown(ssl); /* bidirectional shutdown */ } SSL_free(ssl); CloseSocket(clientfd); if (resume == 1 && resumeCount == 0) { resumeCount++; /* only do one resume for testing */ continue; } resumeCount = 0; if(!loopIndefinitely) { break; /* out of while loop, done with normal and resume option */ } } /* while(1) */ CloseSocket(sockfd); SSL_CTX_free(ctx); ((func_args*)args)->return_code = 0;#if defined(NO_MAIN_DRIVER) && defined(HAVE_ECC) && defined(FP_ECC) / && defined(HAVE_THREAD_LS) ecc_fp_free(); /* free per thread cache */#endif#ifdef USE_WOLFSSL_MEMORY if (trackMemory) ShowMemoryTracker();#endif#ifdef CYASSL_TIRTOS fdCloseSession(Task_self());#endif#if defined(HAVE_SESSION_TICKET) && defined(HAVE_CHACHA) && / defined(HAVE_POLY1305) TicketCleanup();#endif /* There are use cases when these assignments are not read. To avoid * potential confusion those warnings have been handled here. */ (void) ourKey; (void) verifyCert; (void) doCliCertCheck; (void) useNtruKey; (void) ourDhParam; (void) ourCert;#ifndef CYASSL_TIRTOS return 0;#endif}
开发者ID:agnov8,项目名称:wolfssl,代码行数:101,
注:本文中的CloseSocket函数示例整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。 C++ ClosestPoint函数代码示例 C++ CloseSession函数代码示例 |