示例#1
0
void ipcon_recv_loop(void *param) {
#else
void *ipcon_recv_loop(void *param) {
#endif
	IPConnection *ipcon = (IPConnection*)param;
	unsigned char buffer[RECV_BUFFER_SIZE] = { 0 };

	while(ipcon->recv_loop_flag) {
#ifdef _WIN32
		int length = recv(ipcon->s, (char*)buffer, RECV_BUFFER_SIZE, 0);
#else
		int length = read(ipcon->fd, buffer, RECV_BUFFER_SIZE);
#endif
		if(length == 0) {
			if(ipcon->recv_loop_flag) {
				fprintf(stderr, "Socket disconnected by Server, destroying ipcon\n");
				ipcon_destroy(ipcon);
			}
#ifdef _WIN32
			return;
#else
			return NULL;
#endif
		}
		int handled = 0;
		do {
			handled += ipcon_handle_message(ipcon, buffer + handled);
		} while(handled < length);
	}
#ifndef _WIN32
	return NULL;
#endif
}
示例#2
0
static THREAD_RETURN_TYPE ipcon_receive_loop(void *param) {
	IPConnection *ipcon = (IPConnection*)param;
	unsigned char pending_data[RECV_BUFFER_SIZE] = { 0 };
	int pending_length = 0;

	while(ipcon->thread_receive_flag) {
#ifdef _WIN32
		int length = recv(ipcon->s, (char *)(pending_data + pending_length),
		                  RECV_BUFFER_SIZE - pending_length, 0);

		if(!ipcon->thread_receive_flag) {
			break;
		}

		if(length == SOCKET_ERROR) {
			if (WSAGetLastError() == WSAEINTR) {
				continue;
			}

			fprintf(stderr, "A socket error occurred, destroying IPConnection\n");
			ipcon_destroy(ipcon);
			THREAD_RETURN;
		}
#else
		int length = read(ipcon->fd, pending_data + pending_length,
		                  RECV_BUFFER_SIZE - pending_length);

		if(!ipcon->thread_receive_flag) {
			break;
		}

		if(length < 0) {
			if (errno == EINTR) {
				continue;
			}

			fprintf(stderr, "A socket error occurred, destroying IPConnection\n");
			ipcon_destroy(ipcon);
			THREAD_RETURN;
		}
#endif

		if(length == 0) {
			if(ipcon->thread_receive_flag) {
				fprintf(stderr, "Socket disconnected by Server, destroying IPConnection\n");
				ipcon_destroy(ipcon);
			}
			THREAD_RETURN;
		}

		pending_length += length;

		while(true) {
			if(pending_length < 4) {
				// Wait for complete header
				break;
			}

			length = ipcon_get_length_from_data(pending_data);

			if(pending_length < length) {
				// Wait for complete packet
				break;
			}

			ipcon_handle_message(ipcon, pending_data);
			memmove(pending_data, pending_data + length, pending_length - length);
			pending_length -= length;
		}
	}

	THREAD_RETURN;
}