Exemple #1
0
		int ThreadLoop::SendMessageToClient(unsigned int idx)
		{
			if (idx >= m_iMaxSocketNum || m_pSocket[idx].socket_fd == -1)
				return -1;

			size_t send_size = 4096;
			size_t iBufferLen;
			int iRet;
			int iSendSize;

			while (1)
			{
				iRet = m_bufferPool.GetBuffer(m_pSocket[idx].out_data_idx, m_buff, send_size, iBufferLen);
				if (iRet)
				{
					AUX_ERRORLOG("GetBuffer fail iRet[%d]", iRet);
					closeLink(idx);
					return -1;
				}

				if (0 == iBufferLen)
				{
					AUX_DEBUGLOG("not data to send ");
					m_pSocket[idx].wait_event &= (~EPOLLOUT);
					m_epollMng.ModFd(m_pSocket[idx].socket_fd, idx, m_pSocket->wait_event);
					return 0;
				}

				iSendSize = send(m_pSocket[idx].socket_fd, m_buff,iBufferLen, 0);
				if (-1 == iSendSize)
				{
					// if error had happened,do not send other info ,just break;
					if (errno != EAGAIN && errno != EWOULDBLOCK)
					{
						AUX_ERRORLOG("sned fail errno[%d],need close it", errno);
						closeLink(idx);
						return -1;
					}

					break;
				}

				// skip top data;
				iRet = m_bufferPool.SkipData(m_pSocket[idx].out_data_idx, iSendSize);
				if (iRet)
				{
					AUX_ERRORLOG("skip error [%d]", iRet);
					closeLink(idx);
					return -1;
				}
			}

			return 0;
		}
Exemple #2
0
void Html::link(	const String &url,
			const String &txt,
			String id,
			bool newTab)
{
	openLink(url, id, newTab);
	text(txt);
	closeLink();
}
Exemple #3
0
		int ThreadLoop::WaitConnection()
		{
			long long key;
			int iEpollEventFlag;
			int iHadMessageCount = 0;

			while (0 == m_epollMng.GetReadyEvent(key, iEpollEventFlag) && iHadMessageCount++ < 100)
			{
				unsigned int idx = key;

				if (m_pSocket[idx].socket_type == tcp_socket)
				{
					if ((iEpollEventFlag & EPOLLHUP) || (iEpollEventFlag & EPOLLERR))
					{
						closeLink(idx);
						continue;
					}

					// read;
					if ((iEpollEventFlag & EPOLLIN))
					{
						RecvClientMessage(idx);
					}

					// write;
					if (iEpollEventFlag & EPOLLOUT)
					{
						SendMessageToClient(idx);
					}
				}
				else if (m_pSocket[idx].socket_type == fifo_socket && 
						 m_pSocket[idx].socket_fd == m_fromBQueueMng.Notify().getReadNotifyFD())
				{
					// read BModule message;
					if (iEpollEventFlag & EPOLLIN)
					{
						ProcBModuleMessage();
					}
					
					// check error;
					if ((iEpollEventFlag&EPOLLERR) || (iEpollEventFlag&EPOLLHUP))
					{
						ERRLOG("notify fd epoll error events[%d]", iEpollEventFlag);
					}

				}
				
			}

			m_consumeMessage += iHadMessageCount;
			return 0;
		}
Exemple #4
0
bool FSUIPC::write(DWORD offset, DWORD size, void* data)
{
    if (!m_link_ok) m_link_ok = openLink();
    if (!m_link_ok) return false;
    DWORD error = 0;
    bool ret = FSUIPC_Write(offset, size, data, &error);
    if (!ret) 
    {
        Logger::log(QString("FSUIPC:write: Error: %1").arg(getErrorText(error)));
        fflush(stdout);
        closeLink();
    }
    return ret;
}
Exemple #5
0
void Html::header(const String &title, bool blank, const String &redirect)
{
	mBlank = blank;

	*mStream<<"<!DOCTYPE html>\n";
	*mStream<<"<html>\n";
	*mStream<<"<head>\n";
	if(blank) *mStream<<"<title>"<<title<<"</title>\n";
	else if(title.empty()) *mStream<<"<title>"<<APPNAME<<"</title>\n";
	else *mStream<<"<title>"<<title<<" - "<<APPNAME<<"</title>\n";
	*mStream<<"<meta http-equiv=\"content-type\" content=\"text/html;charset=UTF-8\">\n";
	*mStream<<"<meta name=\"viewport\" content=\"width=device-width, initial-scale=1, maximum-scale=1\">\n";
	*mStream<<"<link rel=\"stylesheet\" type=\"text/css\" href=\"/static/style.css\">\n";
	*mStream<<"<link rel=\"shortcut icon\" type=\"image/x-icon\" href=\"/static/favicon.ico\">\n";
	if(!redirect.empty()) *mStream<<"<meta http-equiv=\"refresh\" content=\"3;URL='"+redirect+"'\">\n";
	*mStream<<"<noscript><meta http-equiv=\"refresh\" content=\"0;url=/static/noscript.html\"></noscript>\n";
	*mStream<<"<script type=\"text/javascript\" src=\"/static/jquery.min.js\"></script>\n";
	*mStream<<"<script type=\"text/javascript\" src=\"/static/jquery.form.min.js\"></script>\n";
	*mStream<<"<script type=\"text/javascript\" src=\"/static/common.js\"></script>\n";
	*mStream<<"<script type=\"text/javascript\" src=\"/static/contacts.js\"></script>\n";
	*mStream<<"<script type=\"text/javascript\" src=\"/static/directory.js\"></script>\n";
	*mStream<<"<script type=\"text/javascript\" src=\"/static/mail.js\"></script>\n";
	*mStream<<"<base target=\"_parent\">\n";

	// Load specific CSS on touch devices
	javascript("var deviceAgent = navigator.userAgent.toLowerCase();\n\
if(deviceAgent.indexOf('android') >= 0 || deviceAgent.indexOf('iPhone') >= 0 || deviceAgent.indexOf('iPad') >= 0)\n\
	$('head').append('<link rel=\"stylesheet\" type=\"text/css\" href=\"/static/touchscreen.css\">');");

	*mStream<<"</head>\n";
	*mStream<<"<body>\n";

	open("div","page");

	if(!mBlank)
	{
		open("div","header");
		openLink("/","#backlink"); image("/static/logo.png", APPNAME, "logo"); closeLink();
		open("div","title");
		if(title.empty()) text(APPNAME);
		else text(title);
		close("div");
		close("div");
		//javascript("$('#backlink').click(function(){ window.location.href = getBasePath(1); return false;});");
		open("div","content");
	}
}
Exemple #6
0
		int ThreadLoop::ClearTimeoutSocket()
		{
			static unsigned int last_clear_socket_time = m_tNow.tv_sec;

			if (m_tNow.tv_sec - last_clear_socket_time > 30)
			{
				for (unsigned int i = 0; i < m_iMaxSocketNum; i++)
				{
					if (m_pSocket[i].socket_type == tcp_socket && 
						m_pSocket[i].isset() && 
						(m_tNow.tv_sec - m_pSocket[i].last_active_time) > 60*5)
					{
						closeLink(i);
					}
				}
				last_clear_socket_time = m_tNow.tv_sec;
			}
			return 0;
		}
Exemple #7
0
int main(int argc, char *argv[]) {
  GtkWidget *window = NULL;

  gtk_init(&argc, &argv);

  /* initialize serial link */
  if(initLink(ttyUSB0, 19200) == FALSE) {
    fprintf(stderr, "Error on opening serial port!\n");
    return -1;
  }

  /* initialize main window */
  window = avi_new_appwindow();
  gtk_widget_show_all(window);

  gtk_main();

  closeLink(ttyUSB0);
  return 0;
}
Exemple #8
0
bool FSUIPC::openLink()
{
    closeLink();

    DWORD error = 0;
#if VASFMC_GAUGE
    delete [] m_buffer;
    m_buffer=new BYTE[FSUIPC_BUFFER_SIZE];
    int ret = FSUIPC_Open2(SIM_ANY, &error, m_buffer, FSUIPC_BUFFER_SIZE);
#else
    int ret = FSUIPC_Open(SIM_ANY, &error);
#endif
    if (!ret || error != FSUIPC_ERR_OK) 
    {
//         printf("FSUIPC:openLink: Error: %s\n", getErrorText(error).toLatin1().data());
//         fflush(stdout);
        return false;
    }

    m_link_ok = true;
    return true;
};
Exemple #9
0
/*!
 * Minimal HTML formatter for error messages
 *
 * Features:
 * ' * ' => html link or nicer bullet point
 * 'http://' / 'https://' => link
 * "..." => "<b>...</b>"
 *
 * \param newline Keep don't convert newlines to &lt;br&gr; tags.
 * \param ul      Use HTML lists.
 */
static std::string formatAsHtml(const std::string & text, bool newline, bool ul = false) {
	
	std::stringstream oss;
	std::istringstream iss(text);
	
	bool list = false, first = true;
	
	std::string line;
	while(!std::getline(iss, line).fail()) {
		
		size_t i = 0;
		
		if(line.length() >= 3 && line.compare(0, 3, " * ", 3) == 0) {
			i += 3;
			
			if(ul && !list) {
				oss << "<ul>";
				list = true;
			} else if(!ul && !first) {
				oss << (newline ? "\n" : "<br>");
			}
			
			oss << (ul ? "<li>" : " &#8226; "); // &bull;
			
		} else if(list) {
			oss << "</ul>";
			list = false;
		} else if(!first) {
			oss << (newline ? "\n" : "<br>");
		}
		first = false;
		
		bool italic = false;
		if(line.length() >= i + 3 && line.compare(i, 3, "-> ", 3) == 0) {
			i += 3;
			oss << "&#8594;&#160; <i>"; // &rarr;&nbsp;
			italic = true;
		}
		
		bool quote = false, link = false;
		
		size_t link_start = 0;
		
		for(; i < line.length(); i++) {
			
			if(link && !isAllowedInUrl(line[i])) {
				closeLink(oss, link_start);
				link = false;
			}
			
			if(line[i] == '<') {
				oss << "&lt;";
			} else if(line[i] == '>') {
				oss << "&gt;";
			} else if(line[i] == '"') {
				if(!quote) {
					oss << "\"<b>";
				} else {
					oss << "</b>\"";
				}
				quote = !quote;
			} else if(!link && line.compare(i, 7, "http://", 7) == 0) {
				oss << "<a href=\"";
				link_start = oss.tellp(), link = true;
				oss << "http://";
				i += 6;
			} else if(!link && line.compare(i, 8, "https://", 8) == 0) {
				oss << "<a href=";
				link_start = oss.tellp(), link = true;
				oss << "https://";
				i += 7;
			} else {
				oss << line[i];
			}
			
		}
		
		if(link) {
			closeLink(oss, link_start);
		}
		
		if(quote) {
			oss << "</b>";
		}
		
		if(italic) {
			oss << "</i>";
		}
		
	}
	
	return oss.str();
}
int SerialPortMacOS::openLink()
{
    struct termios tty;
    //memset(&tty, 0, sizeof(tty));

    // Make sure no tty connection is already running (in that case, openLink() will do a reconnection)
    closeLink();

    // Check if another instance is using this port
    if (isLocked() == true)
    {
        TRACE_ERROR(SERIAL, "Cannot connect to serial port: '%s': interface is locked!\n", ttyDevicePath.c_str());
        goto OPEN_LINK_LOCKED;
    }

    // Open tty device
    // O_RDWR: Request opening the file read/write
    // O_NOCTTY: If the named file is a terminal device, don't make it the controlling terminal for the process
    // O_EXLOCK: Acquire an exclusive lock on the file.

    ttyDeviceFileDescriptor = open(ttyDevicePath.c_str(), O_RDWR | O_NOCTTY);
    if (ttyDeviceFileDescriptor < 0)
    {
        TRACE_ERROR(SERIAL, "Unable to open device on serial port: '%s', %s(%d)\n",
                    ttyDevicePath.c_str(), strerror(errno), errno);
        goto OPEN_LINK_ERROR;
    }

    // Lock device
    setLock();

    // Get the current options and save them so we can restore the default settings later.
    if (tcgetattr(ttyDeviceFileDescriptor, &tty) == -1)
    {
        TRACE_ERROR(SERIAL, "Error getting tty attributes %s - %s(%d).\n",
                    ttyDevicePath.c_str(), strerror(errno), errno);
        goto OPEN_LINK_ERROR;
    }

    // ttyDeviceBaudRateFlag: flag from termios.h
    // CS8: setting the character size
    // CLOCAL: ?
    // CREAD: input can be read from the terminal
    // IGNPAR: ignore bit parity

    // Set newtio attributes
    tty.c_cflag     = CS8 | CLOCAL | CREAD;
    tty.c_iflag     = IGNPAR;
    tty.c_oflag     = 0;
    tty.c_lflag     = 0;
    tty.c_cc[VTIME] = 0;
    tty.c_cc[VMIN]  = 0;

    sleep(1); // FIXME why is this necessary for our serial port to work?

    tcflush(ttyDeviceFileDescriptor, TCIFLUSH);
    // Cause the new options to take effect immediately.
    if (tcsetattr(ttyDeviceFileDescriptor, TCSANOW, &tty) == -1)
    {
       TRACE_ERROR(SERIAL, "Error setting tty attributes %s - %s(%d).\n",
                  ttyDevicePath.c_str(), strerror(errno), errno);
       goto OPEN_LINK_ERROR;
    }

    TRACE_1(SERIAL, "Current input baud rate is %d\n", (int)cfgetispeed(&tty));
    TRACE_1(SERIAL, "Current output baud rate is %d\n", (int)cfgetospeed(&tty));

    sleep(1); // FIXME why is this necessary for our serial port to work?

    if (ttyDeviceBaudRate < 1)
    {
        TRACE_ERROR(SERIAL, "Unable to set baud rate to '%i'bps: invalid value\n", ttyDeviceBaudRate);
        goto OPEN_LINK_ERROR;
    }

    // Set custom serial infos?
    {
        cfsetspeed(&tty, ttyDeviceBaudRateFlag);

        // The IOSSIOSPEED ioctl can be used to set arbitrary baud rates
        // other than those specified by POSIX. The driver for the underlying serial hardware
        // ultimately determines which baud rates can be used. This ioctl sets both the input
        // and output speed.

        if (ioctl(ttyDeviceFileDescriptor, IOSSIOSPEED, &(ttyDeviceBaudRate)) == -1)
        {
            TRACE_ERROR(SERIAL, "Error calling ioctl(..., IOSSIOSPEED, ...) %s - %s(%d).\n",
                        ttyDevicePath.c_str(), strerror(errno), errno);
        }

        // Print the new input and output baud rates. Note that the IOSSIOSPEED ioctl interacts with the serial driver
        // directly bypassing the termios struct. This means that the following two calls will not be able to read
        // the current baud rate if the IOSSIOSPEED ioctl was used but will instead return the speed set by the last call
        // to cfsetspeed.

        TRACE_1(SERIAL, "Input baud rate changed to %d\n", (int) cfgetispeed(&tty));
        TRACE_1(SERIAL, "Output baud rate changed to %d\n", (int) cfgetospeed(&tty));

        unsigned long mics = 1UL;
        if (ioctl(ttyDeviceFileDescriptor, IOSSDATALAT, &mics) == -1)
        {
            // set latency to 1 microsecond
            TRACE_ERROR(SERIAL, "Error setting read latency %s - %s(%d).\n",
                        ttyDevicePath.c_str(), strerror(errno), errno);
            goto OPEN_LINK_ERROR;
        }
    }
/*
    // Set custom serial infos?
    if (ttyCustomSpeed == true || ttyLowLatency == true)
    {
        struct serial_struct serinfo;
        memset(&serinfo, 0, sizeof(serinfo));

        // Get current serial_struct values
        if (ioctl(ttyDeviceFileDescriptor, TIOCGSERIAL, &serinfo) < 0)
        {
            TRACE_ERROR(SERIAL, "Cannot get serial infos structure from serial port: '%s'\n", ttyDevicePath.c_str());
            goto OPEN_LINK_ERROR;
        }

        if (ttyCustomSpeed == true)
        {
            serinfo.flags &= ~ASYNC_SPD_MASK;
            serinfo.flags |= ASYNC_SPD_CUST;
            serinfo.custom_divisor = serinfo.baud_base / ttyDeviceBaudRate;
            if (serinfo.custom_divisor < 1)
            {
                serinfo.custom_divisor = 1;
            }
        }

        if (ttyLowLatency == true)
        {
            serinfo.flags |= ASYNC_LOW_LATENCY;
        }

        // Set serial_struct
        if (ioctl(ttyDeviceFileDescriptor, TIOCSSERIAL, &serinfo) < 0)
        {
            TRACE_ERROR(SERIAL, "Cannot set serial infos structure with custom baud divisor (%s) to serial port: '%s'\n", ttyDeviceBaudRate, ttyDevicePath.c_str());
            goto OPEN_LINK_ERROR;
        }
    }
*/
    return 1;

OPEN_LINK_ERROR:
    closeLink();
    return 0;

OPEN_LINK_LOCKED:
    closeLink();
    return -1;
}
SerialPortMacOS::~SerialPortMacOS()
{
    closeLink();
}
int SerialPortWindows::openLink()
{
    DCB Dcb;
    COMMTIMEOUTS Timeouts;
    DWORD dwError;

    // Make sure no tty connection is already running
    closeLink();

    // Check if another instance is using this port
    if (isLocked() == true)
    {
        TRACE_ERROR(SERIAL, "Cannot connect to serial port: '%s': interface is locked!\n", ttyDevicePath.c_str());
        goto OPEN_LINK_LOCKED;
    }

    // Open tty device
#ifdef UNICODE
    ttyDeviceFileDescriptor = CreateFileW(stringToLPCWSTR(ttyDeviceName), GENERIC_READ|GENERIC_WRITE, 0, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
#else
    ttyDeviceFileDescriptor = CreateFileA(ttyDeviceName.c_str(), GENERIC_READ|GENERIC_WRITE, 0, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
#endif
    if (ttyDeviceFileDescriptor == INVALID_HANDLE_VALUE)
    {
        TRACE_ERROR(SERIAL, "Unable to open device: '%s' error: '%i'\n", ttyDeviceName.c_str(), GetLastError());
        goto OPEN_LINK_ERROR;
    }

    // Lock device
    setLock();

    // Setting communication property
    Dcb.DCBlength = sizeof(DCB);
    if (GetCommState(ttyDeviceFileDescriptor, &Dcb) == FALSE)
    {
        TRACE_ERROR(SERIAL, "Unable to get communication state on '%s'\n", ttyDevicePath.c_str());
        goto OPEN_LINK_ERROR;
    }

    // Set baudrate
    Dcb.BaudRate            = (DWORD)ttyDeviceBaudRate;
    Dcb.ByteSize            = 8;                    // Data bit = 8bit
    Dcb.Parity              = NOPARITY;             // No parity
    Dcb.StopBits            = ONESTOPBIT;           // Stop bit = 1
    Dcb.fParity             = NOPARITY;             // No Parity check
    Dcb.fBinary             = 1;                    // Binary mode
    Dcb.fNull               = 0;                    // Get Null byte
    Dcb.fAbortOnError       = 1;
    Dcb.fErrorChar          = 0;
    // Not using XOn/XOff
    Dcb.fOutX               = 0;
    Dcb.fInX                = 0;
    // Not using H/W flow control
    Dcb.fDtrControl         = DTR_CONTROL_DISABLE;
    Dcb.fRtsControl         = RTS_CONTROL_DISABLE;
    Dcb.fDsrSensitivity     = 0;
    Dcb.fOutxDsrFlow        = 0;
    Dcb.fOutxCtsFlow        = 0;

    if (SetCommState(ttyDeviceFileDescriptor, &Dcb) == FALSE)
    {
        TRACE_ERROR(SERIAL, "Unable to set communication state on '%s'\n", ttyDevicePath.c_str());
        goto OPEN_LINK_ERROR;
    }
    if (SetCommMask(ttyDeviceFileDescriptor, 0) == FALSE) // Not using Comm event
    {
        TRACE_ERROR(SERIAL, "Unable to set communication mask on '%s'\n", ttyDevicePath.c_str());
        goto OPEN_LINK_ERROR;
    }
    if (SetupComm(ttyDeviceFileDescriptor, 8192, 8192) == FALSE) // Buffer size (Rx,Tx)
    {
        TRACE_ERROR(SERIAL, "Unable to setup communication on '%s'\n", ttyDevicePath.c_str());
        goto OPEN_LINK_ERROR;
    }
    if (PurgeComm(ttyDeviceFileDescriptor, PURGE_TXABORT|PURGE_TXCLEAR|PURGE_RXABORT|PURGE_RXCLEAR) == FALSE) // Clear buffer
    {
        TRACE_ERROR(SERIAL, "Unable to purge communication on '%s'\n", ttyDevicePath.c_str());
        goto OPEN_LINK_ERROR;
    }
    if (ClearCommError(ttyDeviceFileDescriptor, &dwError, NULL) == FALSE)
    {
        TRACE_ERROR(SERIAL, "Unable to clear communication errors on '%s'\n", ttyDevicePath.c_str());
        goto OPEN_LINK_ERROR;
    }
    if (GetCommTimeouts(ttyDeviceFileDescriptor, &Timeouts) == FALSE)
    {
        TRACE_ERROR(SERIAL, "Unable to get communication timeouts on '%s'\n", ttyDevicePath.c_str());
        goto OPEN_LINK_ERROR;
    }

    // Timeout (Not using timeout)
    // Immediatly return
    Timeouts.ReadIntervalTimeout         = 0;
    Timeouts.ReadTotalTimeoutMultiplier  = 0;
    Timeouts.ReadTotalTimeoutConstant    = 1; // Must not be zero
    Timeouts.WriteTotalTimeoutMultiplier = 0;
    Timeouts.WriteTotalTimeoutConstant   = 0;

    if (SetCommTimeouts(ttyDeviceFileDescriptor, &Timeouts) == FALSE)
    {
        TRACE_ERROR(SERIAL, "Unable to set communication timeouts on '%s'\n", ttyDevicePath.c_str());
        goto OPEN_LINK_ERROR;
    }

    return 1;

OPEN_LINK_ERROR:
    closeLink();
    return 0;

OPEN_LINK_LOCKED:
    closeLink();
    return -1;
}
SerialPortWindows::~SerialPortWindows()
{
    closeLink();
}
Exemple #14
0
		int ThreadLoop::RecvClientMessage(unsigned int idx)
		{
			if (m_pSocket[idx].socket_type != tcp_socket || idx >= m_iMaxSocketNum || m_pSocket[idx].socket_fd == -1)
				return -1;

			int iReadSize = recv(m_pSocket[idx].socket_fd, m_buff, COMMON_BUFF_SIZE, MSG_DONTWAIT);
			int iRet;

			if (iReadSize > 0)
			{
				m_pSocket[idx].last_active_time = m_tNow.tv_sec;
				iRet = m_bufferPool.AppendBuffer(m_pSocket[idx].in_data_idx, m_buff, iReadSize);
				if (iRet)
				{
					AUX_ERRORLOG("append fail iRet[%d]", iRet);
					return -1;
				}

				while (m_bufferPool.Size(m_pSocket[idx].in_data_idx) >= 10)
				{
					// send to B
					TMessageQueueHeader *pHeader = (TMessageQueueHeader *)m_buff;
					pHeader->data.sock_fd_idx = idx;
					pHeader->message_type = tcp_data;
					pHeader->us_client_ip_net_order = m_pSocket[idx].us_client_ip_net_order;
					pHeader->us_client_port = m_pSocket[idx].us_client_port;
					pHeader->us_listen_port = m_pSocket[idx].us_listen_port;

					size_t iIndicateReadSize = 10;
					size_t iOutLen;
					iRet = m_bufferPool.GetBuffer(m_pSocket[idx].in_data_idx, m_buff + sizeof(TMessageQueueHeader), iIndicateReadSize, iOutLen);
					if (iRet)
					{
						AUX_ERRORLOG("GetBuffer iRet[%d]", iRet);
						return -1;
					}
					else
					{
						iRet = m_toBQueueMng.push_back(m_buff, iOutLen + sizeof(TMessageQueueHeader));
						if (iRet)
						{
							AUX_ERRORLOG("toBQueue push_back iRet[%d]", iRet);
							return -1;
						}
					}

					iRet = m_bufferPool.SkipData(m_pSocket[idx].in_data_idx, iOutLen);
					if (iRet)
					{
						AUX_ERRORLOG("skipdata error iRet[%d]", iRet);
						return -1;
					}
					AUX_DEBUGLOG("data is complete, left size[%zu]",
						m_bufferPool.Size(m_pSocket[idx].in_data_idx));
				}

				AUX_DEBUGLOG("recv size[%d]", iReadSize);
				m_consumeMessage++;
			}
			else if (0 == iReadSize || 
				(-1 == iReadSize && (EWOULDBLOCK != errno && EAGAIN != errno)))
			{
				// if recv return 0 means other peer is closed see [man recv]
				// or -1 == iReadSize and errnor not (EWOULDBLOCK OR EAGAIN)
				closeLink(idx);
				AUX_DEBUGLOG("close link errnor[%d],iReadSize[%d]",errno,iReadSize);
			}
			m_consumeMessage++;
			return 0;
		}
Exemple #15
0
		int ThreadLoop::AcceptConnection()
		{
			int consumeMessage = 0;

			if (m_queueMng.get_usage_size() > 0)
			{
				while (consumeMessage < 100)
				{
					unsigned int iOutLen = 0;
					if (0 == m_queueMng.top(m_buff, COMMON_BUFF_SIZE, iOutLen) && 0 != iOutLen)
					{
						m_queueMng.skip_top();
						consumeMessage++;

						TMessageQueueHeader *pHeader = (TMessageQueueHeader *)m_buff;
						int idx = allocSocketNode();

						if (-1 == idx)
						{
							AUX_ERRORLOG("allocSocketNode fail [%d]", idx);
							break;
						}

						m_pSocket[idx].socket_fd = pHeader->data.new_sock_fd;
						m_pSocket[idx].us_listen_port = pHeader->us_listen_port;
						m_pSocket[idx].us_client_ip_net_order = pHeader->us_client_ip_net_order;
						m_pSocket[idx].us_client_port = pHeader->us_client_port;
						m_pSocket[idx].last_active_time = m_tNow.tv_sec;
						m_pSocket[idx].wait_event = (EPOLLIN | EPOLLERR | EPOLLHUP);
						m_pSocket[idx].socket_type = tcp_socket;
						m_pSocket[idx].in_data_idx = -1;
						m_pSocket[idx].out_data_idx = -1;

						int64_t in_data_idx, out_data_idx;
						int iRet = m_bufferPool.GetOneFreeKey(in_data_idx);

						if (0 != iRet)
						{
							closeLink(idx);
							AUX_ERRORLOG("buffer pool getonefreekey fail iRet[%d]", iRet);
							break;
						}
						m_pSocket[idx].in_data_idx = in_data_idx;

						iRet = m_bufferPool.GetOneFreeKey(out_data_idx);
						if (0 != iRet)
						{
							closeLink(idx);
							m_bufferPool.FreeBuffer(in_data_idx);
							AUX_ERRORLOG("buffer pool getonefreekey fail iRet[%d]", iRet);
							break;
						}
						m_pSocket[idx].out_data_idx = out_data_idx;

						AUX_DEBUGLOG("idx [%d]", idx);
						m_epollMng.AddFd(m_pSocket[idx].socket_fd, idx, m_pSocket[idx].wait_event);
					}
					else
					{
						m_queueMng.skip_top();
						break;
					}
				}
			}

			m_consumeMessage += consumeMessage;
			if (0 != consumeMessage)
				m_queueMng.Notify().consumeNotify(consumeMessage);
			else
				m_queueMng.Notify().consumeNotify(1);
			return 0;
		}