当前位置: 首页>>代码示例>>C++>>正文


C++ CloseSocket函数代码示例

本文整理汇总了C++中CloseSocket函数的典型用法代码示例。如果您正苦于以下问题:C++ CloseSocket函数的具体用法?C++ CloseSocket怎么用?C++ CloseSocket使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。


在下文中一共展示了CloseSocket函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C++代码示例。

示例1: WndProc

LRESULT 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,代码来源:RemotePad+Server.cpp

示例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,代码来源:start_agent.c

示例3: CloseSocket

void XLCDproc::Stop()
{
  CloseSocket();
  m_bStop = true;
}
开发者ID:Alxandr,项目名称:spotyxbmc2,代码行数:5,代码来源:XLCDproc.cpp

示例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,代码来源:server.c

示例5: RecvFinish

void 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,代码来源:connection.c

示例6: sd_listen_fds

void 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,代码来源:socket-manager.cpp

示例7: Sys_Net_DeleteSocket

void Sys_Net_DeleteSocket(struct SysNetData *netdata, struct SysSocket *socket)
{
	CloseSocket(socket->s);
	FreeVec(socket);
}
开发者ID:classicQ,项目名称:classicQ.github.io,代码行数:5,代码来源:net_amitcp.c

示例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,代码来源:client.c

示例9: testserver

int 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,代码来源:webserver.c

示例10: socket

int 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,代码来源:network.cpp

示例11: memset

void 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,代码来源:ur_realtime_communication.cpp

示例12: OnDoorRequest

int 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,代码来源:jPush.c

示例13: WSAStartup

int 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,代码来源:WebRequest.cpp

示例14: memcpy

void * 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,代码来源:client_core.cpp

示例15: CHROMIUM_LOG

void
NfcConsumer::OnConnectError()
{
    CHROMIUM_LOG("NFC: %s\n", __FUNCTION__);
    CloseSocket();
}
开发者ID:chardis,项目名称:gecko-dev,代码行数:6,代码来源:Nfc.cpp


注:本文中的CloseSocket函数示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。