Beispiel #1
0
int EgSock::Connect(const char* ip, uint16_t port, function<void(sp_EgSock)> callback) 
{
	_fd = CreateSocket();
	SetNonblock(fd);
	SetNodelay(fd);

	_peer_ip = ip;
	_port = port;
	_state = EG_SOCK_CONNECTING;
	_callback = callback;

	sockaddr_in serv_addr;
	SetAddr(ip, port,  &serv_addr);
	if (connect(_fd, (sockaddr*)&serv_addr, sizeof(serv_addr)) == SOCKET_ERROR) {
		if (!((errno == EINPROGRESS) || (errno == EWOULDBLOCK))) {
			loge("connect failed, err_code=%d", errno);
			close(_fd);
			throw egex("connect failed, errno=%d", errno);
		}
	} else {
		_state = EG_SOCK_CONNECTED;
		callback(shared_from_this());
	}
	return _fd;
}
Beispiel #2
0
void EgSock::_OnAccept()
{
	int sessionFd = 0;
	sockaddr_in peer_addr;
	socklen_t addr_len = sizeof(sockaddr_in);
	char ip_str[64];
	while((sessionFd = accept(fd, (sockaddr*)&peer_addr, &addr_len)) != INVALID_SOCKET) {
		EgSock* sock = new EgSock();
		uint32_t ip = ntohl(peer_addr.sin_addr.s_addr);
		uint16_t port = ntohs(peer_addr.sin_port);
		snprintf(ip_str, sizeof(ip_str), "%d.%d.%d.%d", ip >> 24, (ip >> 16) & 0xFF, (ip >> 8) & 0xFF, ip & 0xFF);
		sock->SetPeerIp(ip_str);
		sock->SetPeerPort(port);
		sock->SetFd(sessionFd);
		sock->SetCallback(_callback);
		SetNodelay(sessionFd);
		SetNonblock(sessionFd);
		EgDispatch::Instance()->AddEvent(sessionFd);
	}
}
Beispiel #3
0
extern	NETFILE	*
SocketToNet(
	int		fd)
{
	NETFILE	*fp;

	fp = NewNet();
	SetNodelay(fd);
	fp->fd = fd;
	fp->read = FD_Read;
	fp->write = FD_Write;
	fp->close = FD_Close;
#if	1
	fp->buff = xmalloc(SIZE_BUFF);
	memclear(fp->buff, SIZE_BUFF);
	fp->size = SIZE_BUFF;
	fp->ptr = 0;
#endif
	return	(fp);
}