Example #1
0
int CreateMailSocket()		/* open socket to mail server */
{
	int ms;
	char buffer[256];

	ms = ConnectServer(MAILSERVER, SMTPPORT);
	if (ms < 0)
		ms = ConnectServer("127.0.0.1", SMTPPORT);
	if (ms > 0)
	{
		while (net_gets(ms, buffer, sizeof(buffer)))
		{
			if (strncmp(buffer, "220-", 4))
				break;
		}
		if (strncmp(buffer, "220 ", 4))
		{
			CloseMailSocket(ms);
			return -1;
		}

		net_printf(ms, "HELO bbs\r\n");
		while (net_gets(ms, buffer, sizeof(buffer)))
		{
			if (strncmp(buffer, "250-", 4))
				break;
		}
		if (strncmp(buffer, "250 ", 4))
		{
			CloseMailSocket(ms);
			return -1;
		}
	}
	return ms;
}
Example #2
0
ModResult ModuleSpanningTree::HandleConnect(const CommandBase::Params& parameters, User* user)
{
	for (std::vector<reference<Link> >::iterator i = Utils->LinkBlocks.begin(); i < Utils->LinkBlocks.end(); i++)
	{
		Link* x = *i;
		if (InspIRCd::Match(x->Name, parameters[0], ascii_case_insensitive_map))
		{
			if (InspIRCd::Match(ServerInstance->Config->ServerName, x->Name, ascii_case_insensitive_map))
			{
				user->WriteRemoteNotice(InspIRCd::Format("*** CONNECT: Server \002%s\002 is ME, not connecting.", x->Name.c_str()));
				return MOD_RES_DENY;
			}

			TreeServer* CheckDupe = Utils->FindServer(x->Name);
			if (!CheckDupe)
			{
				user->WriteRemoteNotice(InspIRCd::Format("*** CONNECT: Connecting to server: \002%s\002 (%s:%d)", x->Name.c_str(), (x->HiddenFromStats ? "<hidden>" : x->IPAddr.c_str()), x->Port));
				ConnectServer(x);
				return MOD_RES_DENY;
			}
			else
			{
				user->WriteRemoteNotice(InspIRCd::Format("*** CONNECT: Server \002%s\002 already exists on the network and is connected via \002%s\002", x->Name.c_str(), CheckDupe->GetParent()->GetName().c_str()));
				return MOD_RES_DENY;
			}
		}
	}
	user->WriteRemoteNotice(InspIRCd::Format("*** CONNECT: No server matching \002%s\002 could be found in the config file.", parameters[0].c_str()));
	return MOD_RES_DENY;
}
Example #3
0
void Main_OnCommand(HWND hwnd, int id, HWND hwndCtl, UINT codeNotify)
{
    switch(id)
    {
        case IDC_OK:
		{
			if(InitSock())
			{
				SOCKET httpsock = socket(AF_INET , SOCK_STREAM , IPPROTO_TCP);
				if (INVALID_SOCKET == httpsock)  
				{  
					WSACleanup();
					return 0;
				 } 
				if(!ConnectServer(&httpsock,"",110))
				{
					MessageBox(user->hwnd,TEXT("·þÎñÆ÷Á¬½Óʧ°Ü£¡"),TEXT(""),MB_OK || MB_ICONWARNING);
					return 0;
				}
				ret = connectUserMail(httpsock,user->name,user->pass);
				if(ret)
				{
					
				}
			}
		}
        break;
        default:
		break;
    }
}
Example #4
0
int ModuleSpanningTree::HandleConnect(const std::vector<std::string>& parameters, User* user)
{
	for (std::vector<Link>::iterator x = Utils->LinkBlocks.begin(); x < Utils->LinkBlocks.end(); x++)
	{
		if (InspIRCd::Match(x->Name.c_str(),parameters[0]))
		{
			if (InspIRCd::Match(ServerInstance->Config->ServerName, assign(x->Name)))
			{
				RemoteMessage(user, "*** CONNECT: Server \002%s\002 is ME, not connecting.",x->Name.c_str());
				return 1;
			}

			TreeServer* CheckDupe = Utils->FindServer(x->Name.c_str());
			if (!CheckDupe)
			{
				RemoteMessage(user, "*** CONNECT: Connecting to server: \002%s\002 (%s:%d)",x->Name.c_str(),(x->HiddenFromStats ? "<hidden>" : x->IPAddr.c_str()),x->Port);
				ConnectServer(&(*x));
				return 1;
			}
			else
			{
				RemoteMessage(user, "*** CONNECT: Server \002%s\002 already exists on the network and is connected via \002%s\002",x->Name.c_str(),CheckDupe->GetParent()->GetName().c_str());
				return 1;
			}
		}
	}
	RemoteMessage(user, "*** CONNECT: No server matching \002%s\002 could be found in the config file.",parameters[0].c_str());
	return 1;
}
Example #5
0
void TcpClient::HandleOfflineUsers()
{
	vector<User> users = _online_user.GetOfflineUsers(_max_timeout);

	for(int i = 0; i < (int)users.size(); i++) {
		User &user = users[i];
		const char *ip = user._ip.c_str();
		unsigned short port = user._port;

		ITcpServer *svr = (ITcpServer*)user._ext_ptr;
		if( ! svr->ChkChannel(user._user_id)) {
			continue;
		}

		if(ConnectServer(user, 3)) {
			share::Guard guard(_mutex);

			map<string, vector<char> >::iterator it = _cache.find(user._user_id);
			if(it != _cache.end()) {
				SendData(user._fd, &it->second[0], it->second.size());
				OUT_HEX(ip, port, "SEND", &it->second[0], it->second.size());

				_cache.erase(it);
			}
		}

		_online_user.AddUser(user._user_id, user);
	}
}
// 登录
bool CLiveChatClient::Login(const string& user, const string& password, const string& deviceId, CLIENT_TYPE clientType, USER_SEX_TYPE sexType, AUTH_TYPE authType)
{
	bool result = false;

	FileLog("LiveChatClient", "CLiveChatClient::Login() begin");

	if (!user.empty()
		&& !password.empty()
		&& !deviceId.empty()
		&& ConnectServer())
	{
		m_user = user;
		m_password = password;
		m_deviceId = deviceId;
		m_clientType = clientType;
		m_sexType = sexType;
		m_authType = authType;

		result = true;
	}

	FileLog("LiveChatClient", "CLiveChatClient::Login() end");

	return result;
}
Example #7
0
int reportwrite(char*ip, u64_t blocknum, int port, int status) {
	s64_t sockfd = ConnectServer(ip, port);
	u64_t total_len = 0;
	char* result_report;
	char* title = "WRITE_OK";
	char* name = "Blocknum";
	char blnum[64];
	sprintf(blnum, "%lld", blocknum);
	total_len += strlen(title) + 2;
	total_len += strlen(name) + strlen(blnum) + 4;
	total_len += 2;
	if ((result_report = malloc(total_len)) == NULL) {
		perror("fail to malloc\n");
		return -1;
	}
	strcpy(result_report, title);
	result_report += strlen(title);
	*result_report++ = '\r';
	*result_report++ = '\n';
	strcpy(result_report, name);
	result_report += strlen(name);
	*result_report++ = ':';
	*result_report++ = ' ';
	strcpy(result_report, blnum);
	result_report += strlen(blnum);
	*result_report++ = '\r';
	*result_report++ = '\n';
	*result_report++ = '\r';
	*result_report++ = '\n';
	sendinfo(sockfd, result_report, total_len);
	return 0;
}
Example #8
0
bool  CMySocket::TestContinue()
{
	if (!m_bIM || !ConnectServer())
	{
		return false;
	}

	//发送ping包接续连接试试
	COM_SEND_PING SendInfo(VERSION);
	SendInfo.o.online_flag = ((CChatManager*)m_receiveObj)->m_userInfo.UserInfo.onlineflag;
	((CChatManager*)m_receiveObj)->SendPackTo(&SendInfo, 0, 0);

	fd_set fd;;
	FD_ZERO(&fd);
	FD_SET(m_hSocket, &fd);
	struct timeval val = { 10, 0 };
	int ret = select(m_hSocket + 1, &fd, NULL, NULL, &val);
	if (ret <= 0)
	{
		return false;
	}

	unsigned short plen = (0);
	int n = recv(m_hSocket, (char*)&plen, 2, MSG_PEEK);
	if (n != 2 || 0 == plen)
	{
		g_WriteLog.WriteLog(C_LOG_TRACE, "TestContinue recv:%d,packlen:%hd", n, plen);

		return false;
	}

	return true;
}
Example #9
0
void MsgClient::HandleOfflineUsers()
{
	vector<User> vec_users = _online_user.GetOfflineUsers(3*60);
	for(int i = 0; i < (int)vec_users.size(); i++)
	{
		User &user = vec_users[i];
		if(user._socket_type == User::TcpClient)
		{
			if(user._fd != NULL )
			{
				OUT_WARNING( user._ip.c_str() , user._port , user._user_name.c_str() , "fd %d close socket", user._fd->_fd );
				CloseSocket(user._fd);
			}
		}
		else if(user._socket_type == User::TcpConnClient)
		{
			if( user._fd != NULL )
			{
				OUT_INFO( user._ip.c_str() , user._port , user._user_name.c_str() ,"conn fd %d close socket", user._fd->_fd );
				user.show();
				CloseSocket(user._fd);
				user._fd = NULL;
			}
			if ( ConnectServer(user, 10) ) {
				// 添加列表中。
				_online_user.AddUser( user._user_id, user ) ;
			} else if ( user._connect_info.keep_alive == AlwaysReConn ) {
				// 添加用户
				_online_user.AddUser( user._user_id, user ) ;
			}
		}
	}
}
Example #10
0
void ModuleSpanningTree::ConnectServer(Link* x, Autoconnect* y)
{
	bool ipvalid = true;

	if (InspIRCd::Match(ServerInstance->Config->ServerName, assign(x->Name)))
	{
		ServerInstance->SNO->WriteToSnoMask('l', "CONNECT: Not connecting to myself.");
		return;
	}

	DNS::QueryType start_type = DNS::QUERY_AAAA;
	if (strchr(x->IPAddr.c_str(),':'))
	{
		in6_addr n;
		if (inet_pton(AF_INET6, x->IPAddr.c_str(), &n) < 1)
			ipvalid = false;
	}
	else
	{
		in_addr n;
		if (inet_aton(x->IPAddr.c_str(),&n) < 1)
			ipvalid = false;
	}

	/* Do we already have an IP? If so, no need to resolve it. */
	if (ipvalid)
	{
		/* Gave a hook, but it wasnt one we know */
		TreeSocket* newsocket = new TreeSocket(x, y, x->IPAddr);
		if (newsocket->GetFd() > -1)
		{
			/* Handled automatically on success */
		}
		else
		{
			ServerInstance->SNO->WriteToSnoMask('l', "CONNECT: Error connecting \002%s\002: %s.",
				x->Name.c_str(), newsocket->getError().c_str());
			ServerInstance->GlobalCulls.AddItem(newsocket);
		}
	}
	else if (!DNS)
	{
		ServerInstance->SNO->WriteToSnoMask('l', "CONNECT: Error connecting \002%s\002: Hostname given and m_dns.so is not loaded, unable to resolve.", x->Name.c_str());
	}
	else
	{
		ServernameResolver* snr = new ServernameResolver(*DNS, x->IPAddr, x, start_type, y);
		try
		{
			DNS->Process(snr);
		}
		catch (DNS::Exception& e)
		{
			delete snr;
			ServerInstance->SNO->WriteToSnoMask('l', "CONNECT: Error connecting \002%s\002: %s.",x->Name.c_str(), e.GetReason());
			ConnectServer(y, false);
		}
	}
}
Example #11
0
void PasServer::HandleOfflineUsers()
{
	vector<User> vec_users = _online_user.GetOfflineUsers(3 * 60);
	for (int i = 0; i < (int) vec_users.size(); i++) {
		User user = vec_users[i];
		if (user._socket_type == User::TcpClient) {
			// 移除统计功能的用户
			_datastat.Remove(user._access_code);

			if (user._fd != NULL) {
				OUT_WARNING( user._ip.c_str(), user._port,
						user._user_id.c_str(),
						"HandleOfflineUsers close socket fd %d", user._fd->_fd);
				CloseSocket(user._fd);
			}
		} else if (user._socket_type == User::TcpConnClient) {
			if (user._fd != NULL) {
				OUT_WARNING( user._ip.c_str(), user._port,
						user._user_id.c_str(),
						"TcpConnClient close socket fd %d", user._fd->_fd);
				//	user.show();
				CloseSocket(user._fd);
				user._fd = NULL;
			}

			if (ConnectServer(user, 3)) {
				//连接成功,重新加到在线列表当中。
				if (!_online_user.AddUser(user._user_id, user))
					_online_user.SetUser(user._user_id, user);
			} else if (user._connect_info.keep_alive == AlwaysReConn
					|| user._connect_info.reconnect_times > 0) {
				_online_user.AddUser(user._user_id, user);
			} else {
				if (user._connect_info.reconnect_times <= 0) {
					//  如果用户是下级平台,应该向下级平台发送从链路断开消息
					DownDisconnectInform msg;
					msg.header.msg_len = ntouv32(sizeof(DownDisconnectInform));
					msg.header.access_code = ntouv32(user._access_code);
					msg.header.msg_seq = ntouv32(_proto_parse.get_next_seq());
					msg.header.msg_type = ntouv16(DOWN_DISCONNECT_INFORM);
					msg.error_code = 0x0; //  原因:从链路断开

					char buf[200];
					sprintf(buf, "U_%u", user._access_code);
					//  取主链路fd
					User main_user = _online_user.GetUserByUserId(buf);

					if (!main_user._user_id.empty()) {
						if (SendCrcData(main_user._fd, (const char*) &msg, sizeof(msg))) {
							OUT_INFO( main_user._ip.c_str(), main_user._port, "pas", "DOWN_DISCONNECT_INFORM");
						} else {
							OUT_ERROR( main_user._ip.c_str(), main_user._port, "pas", "DOWN_DISCONNECT_INFORM");
						}
					}
				}
			}
		}
	}
}
Example #12
0
bool CMySocket::Connect(const char* szDomain, unsigned short port)
{
	if (m_szdomian) free(m_szdomian);
	m_szdomian = _strdup(szDomain);
	m_port = port;

	return ConnectServer();
}
Example #13
0
int main(int argc, char **argv) {
	ParseArgs(argc, argv);
	atexit(Cleanup);
	InitHandles();
	ConnectServer();
	InteractiveLoop();
	return 0;
}
Example #14
0
static int DdnsSockComm(ddns_cfg_t *ddns)
{
	struct sockaddr_in ser_addr;
	int sockfd = 0;
	int  ret = 0;
	char   str[32] = {0};
	char **pptr = NULL;
	char DdnsCmdBuf[DDNS_CMD_LEN] = {0};
	char ReceiveBuf[DDNS_RCV_LEN] = {0};
       struct hostent *phost = NULL;
	
	DdnsCmdInfo(DdnsCmdBuf,ddns);
	phost = gethostbyname((char *)ddns->server);
       if (NULL == phost)
	{
	       fprintf(stderr,"gethostbyname() error\n");
		return -1;//
	}
	else
	{
		 pptr=phost->h_addr_list;
		 fprintf(stderr,"gethostbyname() sucssess! address:%s\n",  inet_ntop(phost->h_addrtype, *pptr, str, sizeof(str)));
	}
	ser_addr.sin_family = AF_INET;
	ser_addr.sin_port =  htons(80);
	memcpy(&(ser_addr.sin_addr), *((struct in_addr **)phost->h_addr_list), sizeof(struct in_addr));
	memset(ser_addr.sin_zero,0, sizeof(ser_addr.sin_zero));
       sockfd = socket(AF_INET, SOCK_STREAM, 0);
	if( -1 == sockfd )
	{
		perror(" socket() error\n");
		return -1;
	}	 
	if(ConnectServer(sockfd, (struct sockaddr*)&ser_addr, sizeof(struct sockaddr), 10) != 0)
	{
		perror("connect()");		
		close(sockfd);
		return -1;
	}
	if(send(sockfd, DdnsCmdBuf, strlen(DdnsCmdBuf), 0) == -1)
	{
		perror("send() data to server");
		close(sockfd);
		return -1;
	}
	memset(ReceiveBuf,0,sizeof(ReceiveBuf));
	ret=GetMessageFromServer(sockfd,ReceiveBuf,sizeof(ReceiveBuf));
	close(sockfd);
	if(ret == -1)
	{
		fprintf(stderr,"GetMessagErr!!!\n\n");
		return ret;
	}
	//fprintf(stderr,"recieve:\n%s\n",ReceiveBuf);
	DdnsRspCode(ReceiveBuf);
	return 0;
}
Example #15
0
// 检测用户状态
void PasClient::CheckUserState( UserSession &user )
{
	// 如果当前TCP用户不在线
	if ( user.IsOffline(true) ) {
		// 如果当前用户还没有超时就允许重新连接
		if ( !user.Check( 30, PCC_USER_LOGIN , true ) )
			return ;
		ConnectServer( user, true ) ;
	} else if ( user.IsOffline(false) && user.IsOnline(true) ){
		// 如果当前TCP用户鉴权码为空也不能登陆数据链路
		if ( ! user.IsKey(true) )
			return ;
		if ( ! user.Check( 30, PCC_USER_LOGIN, false ) )
			return ;

		ConnectServer( user, false ) ;
	}
}
Example #16
0
void *thread_function(void *arg)
{
    g_cfd = ConnectServer(g_ip, g_port);
    if (g_cfd < 0)
    {
        printf("ConnectServer failed:%s \n", strerror(errno));
        return NULL;
    }
    return NULL;
}
TCGbool TCGClient::Init_sdk(TCGint argc, TCGchar **argv, const TCGchar* fname)
{
    if (!ParseArgFile(PLAY_CONF_FILE, g_args))
    {
        return TCG_FALSE;
    }

    ConnectServer();

    return TCG_TRUE;
}
Example #18
0
BOOL InitInstance(HANDLE hInstance, int nCmdShow)
{
	g_hInst = (HINSTANCE)hInstance;
	
	INITCOMMONCONTROLSEX	icex;

	icex.dwSize = sizeof(INITCOMMONCONTROLSEX);
	icex.dwICC = ICC_LISTVIEW_CLASSES | ICC_BAR_CLASSES | ICC_INTERNET_CLASSES | ICC_TAB_CLASSES;

	InitCommonControlsEx(&icex);

    g_hMainWnd = CreateWindowEx(0, _T("VirtualClient"), _T("미르의 전설 2 - 가상 클라이언트"), 
							WS_OVERLAPPEDWINDOW|WS_VISIBLE,
							CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT,                 
							NULL, NULL, (HINSTANCE)hInstance, NULL);

	RECT rcMainWnd;

	GetClientRect(g_hMainWnd, &rcMainWnd);

    g_hLogMsgWnd = CreateWindowEx(WS_EX_CLIENTEDGE, WC_LISTVIEW, "", 
							WS_CHILD|WS_VISIBLE|WS_BORDER|LVS_REPORT|LVS_EDITLABELS,
							0, 0, (rcMainWnd.right - rcMainWnd.left), 
							(rcMainWnd.bottom - rcMainWnd.top),
							g_hMainWnd, NULL, (HINSTANCE)hInstance, NULL);

	ListView_SetExtendedListViewStyleEx(g_hLogMsgWnd, 0, LVS_EX_FULLROWSELECT);

	LV_COLUMN	lvc;
	TCHAR		szText[64];

	lvc.mask	= LVCF_FMT | LVCF_WIDTH | LVCF_TEXT | LVCF_SUBITEM;
	lvc.fmt		= LVCFMT_LEFT;
	lvc.cx		= 150;
	lvc.pszText	= szText;

	for (int i = 0; i < 3; i++)
	{
		lvc.iSubItem	= i;
		lvc.pszText		= szLvsLable[i];
		
		ListView_InsertColumn(g_hLogMsgWnd, i, &lvc);
	}

	ShowWindow(g_hMainWnd, SW_SHOW);
	UpdateWindow(g_hMainWnd);

	if (WSAStartup(MAKEWORD(2, 2), &g_wsd) != 0)
		return (FALSE);

	ConnectServer(g_sock, &g_addr, _IDM_SOCKMSG, g_szServerIP, 0, 7000, FD_CONNECT|FD_READ|FD_CLOSE);

	return TRUE;
}
Example #19
0
void ModuleSpanningTree::AutoConnectServers(time_t curtime)
{
	for (std::vector<reference<Autoconnect> >::iterator i = Utils->AutoconnectBlocks.begin(); i < Utils->AutoconnectBlocks.end(); ++i)
	{
		Autoconnect* x = *i;
		if (curtime >= x->NextConnectTime)
		{
			x->NextConnectTime = curtime + x->Period;
			ConnectServer(x, true);
		}
	}
}
Example #20
0
void NetControl::OnOpen()
{
	if(m_pSocket)
	{
		MessageBox(GetActiveWindow(),"已经连接到服务器,请关闭连接再试一次!","警告信息",MB_OK);
		return;
	}
	if(!(m_pSocket=ConnectServer()))
	{
		m_pSocket=NULL;
		return;
	}
}
Example #21
0
//下载消息
LRESULT CPlazaViewItem::OnDownloadFace(WPARAM wParam, LPARAM lParam)
{
	DWORD dwUserID = (DWORD)lParam;
	ASSERT(dwUserID != 0);
	BYTE bFaceVer = (BYTE)wParam;

	//查找存在
	bool bFind = false;
	for ( INT_PTR nIndex = 0; nIndex < m_DownloadInfoArrary.GetCount(); nIndex++ )
	{
		tagDownloadInfo &DownloadInfo = m_DownloadInfoArrary[nIndex];
		if ( DownloadInfo.dwUserID == dwUserID )DownloadInfo.bReference++;
	}

	if ( !bFind )
	{
		tagDownloadInfo DownloadInfo;
		ZeroMemory(&DownloadInfo, sizeof(DownloadInfo));
		DownloadInfo.bFaceVer = bFaceVer;
		DownloadInfo.dwUserID = dwUserID;
		DownloadInfo.bReference = 1;

		//加入队列
		INT_PTR nCount = m_DownloadInfoArrary.GetCount();
		m_DownloadInfoArrary.SetAtGrow(nCount, DownloadInfo);
	}

	//启动下载
	if (m_bStartDownloadFace==false)
	{
		m_bStartDownloadFace=true;

		//状态判断
		if ( m_ClientSocket->GetSocketStatus() != SOCKET_STATUS_CONNECT )
		{
			//链接网络
			if ( ! ConnectServer() ) return FALSE;

			//设置标识
			m_bDownloadConnect = true;
		}

		//投递请求
		CMD_GP_DownloadFace DownloadFace;
		DownloadFace.dwUserID = dwUserID;
		m_ClientSocket->SendData(MDM_GP_USER, SUB_GP_USER_DOWNLOAD_FACE, &DownloadFace, sizeof(DownloadFace));
	}

	return TRUE;
}
bool NetHandler::Init()
{
    m_ServerInitSendFlag = NF_NULL;

    // 加载 [Setup.ini], [LogSetup.ini], [SetupEx.ini]及 [ServerSetup.ini] 配置
    if (!LoadSetup())
    {
        return false;
    }

    InitNetEnv();

    // 创建服务器端
    if (!InitNetServer())
    {
        return false;
    }

    // 连接到LogServer
    if (0 == m_serverSetup.useLogServer)
    {
        Log4c::Warn(ROOT_MODULE,FormatText("GAME_NET_SERVERINVALID", "LogServer"));
    }
    else
    {
        ConnectServer(NF_LOG_SERVER);
    }

    ConnectServer(NF_DB_SERVER); // 连接到DBServer
    ConnectServer(NF_LOGIN_SERVER); // 连接到LoginServer

    // 装载内存影射文件配置
    LoadMapFileSetup();
    CSMClient::GetSM()->InitOk();
    return true;
}
Example #23
0
int main(int argc, char *argv[]){
	if (argc < 3){
		printf("Usage: %s IP Port\n", argv[0]);
		exit(1);
	}
	struct sockaddr_in server;
	memset(&server, '\0', sizeof(server));
	struct addrinfo hints, *res;
	memset(&hints, '\0', sizeof(hints));
	hints.ai_socktype=SOCK_STREAM;
	getaddrinfo(argv[1], argv[2], &hints, &res);
	server=*(struct sockaddr_in *)res->ai_addr;
	freeaddrinfo(res);
	ConnectServer(server);
	return 0;
}
Example #24
0
//---create socket thread
DWORD WINAPI createSocketThread(LPVOID lp)
{
    int err;
	WORD versionRequired;
	WSADATA wsaData;
	versionRequired = MAKEWORD(1,1);
	err = WSAStartup(versionRequired, &wsaData);//协议库的版本信息
	if (err)
	{
		writeFile( log, "Client socket open fail!\n");
		return 1;//结束
	}
	else
	{
		writeFile( log, "Client socket open successful!\n");
	}
	
	
	int flag = -1;
	while(1) 
	{
		if ( CONNECTED_FLAG == false )
		{
            clientSocket = socket( AF_INET, SOCK_STREAM, 0 );
			SOCKADDR_IN clientsock_in;
			clientsock_in.sin_addr.S_un.S_addr = inet_addr( server_ip.c_str() );
			clientsock_in.sin_family = AF_INET;
			clientsock_in.sin_port = htons( port );
			
			flag = connect( clientSocket, (SOCKADDR*)&clientsock_in, sizeof(SOCKADDR) );
		}
		else
			Sleep(1000);
		
		if( flag != -1 && CONNECTED_FLAG == false )
		{
			ConnectServer();
		}
	}
	
	
	closesocket(clientSocket);//关闭
	WSACleanup();
	
	return 0;
	
}
Example #25
0
int sdkTcpConnect(char *ip)
{
    SOCKET client_socket;
    char outdata[1024] = {0};
    int  sdkret = 0;
    int outlen = 0;
    struct sockaddr_in client_addr;
    int ret =0;

    WSADATA wsaData;
    if (WSAStartup(MAKEWORD(2,1),&wsaData)) //调用Windows Sockets DLL
    {
        printf("Winsock无法初始化!\n");
        WSACleanup();
        return NULL;
    }

    client_socket =  socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
    if(client_socket < 0 ) {
        PRINTF("sdkTcpConnect:client_socket error!\n");
        return -1;
    }

    memset(&client_addr ,0, sizeof(client_addr));
    client_addr.sin_family = AF_INET;
    client_addr.sin_port = htons(SDK_LISTEN_PORT);
    client_addr.sin_addr.s_addr = inet_addr(ip);
    u_long mode = 1;
    ioctlsocket(client_socket,FIONBIO,&mode);

    ret = ConnectServer(client_socket,client_addr);
//	connet_num = connect(client_socket , (struct sockaddr *)&client_addr ,sizeof(struct sockaddr));
    if( ret < 0 )
    {
        PRINTF("sdkTcpConnect:connect is error!\n");
        closesocket(client_socket);
        WSACleanup();
        client_socket = -1;
        return -1;
    }
//	g_sdk_cli_sock = client_socket;

    return client_socket;
}
Example #26
0
/////////////////////////// functions ///////////////////////////////////
int Sample::Init()
{
	int err_code = PQMTE_SUCESS;

	// initialize the handle functions of gestures;
	InitFuncOnTG();
	// set the functions on server callback
	SetFuncsOnReceiveProc();
	// connect server
	cout << " connect to server..." << endl;
	if((err_code = ConnectServer()) != PQMTE_SUCESS){
		cout << " connect server fail, socket error code:" << err_code << endl;
		return err_code;
	}
	// send request to server
	cout << " connect success, send request." << endl;
	TouchClientRequest tcq = {0};
	tcq.app_id = GetTrialAppID();
	tcq.type = RQST_RAWDATA_ALL | RQST_GESTURE_ALL;
	if((err_code = SendRequest(tcq)) != PQMTE_SUCESS){
		cout << " send request fail, error code:" << err_code << endl;
		return err_code;
	}
	//////////////you can set the move_threshold when the tcq.type is RQST_RAWDATA_INSIDE;
	//send threshold
	//int move_threshold = 1;// 1 pixel
	//if((err_code = SendThreshold(move_threshold) != PQMTE_SUCESS){
	//	cout << " send threadhold fail, error code:" << err_code << endl;
	//	return err_code;
	//}
	//
	////////////////////////
	//get server resolution
	if((err_code = GetServerResolution(OnGetServerResolution, NULL)) != PQMTE_SUCESS){
		cout << " get server resolution fail,error code:" << err_code << endl;
		return err_code;
	};
	//
	// start receiving
	cout << " send request success, start recv." << endl;
	return err_code;
}
Example #27
0
int reportlist(char* ip, int port) {
	if (getlist() < 0) {
		perror("fail to get list \n");
		return -1;
	}
	s64_t sockfd = ConnectServer(ip, port);
	sbphead = report_head(databuf, req_len);
	build_headp(&send_buf, &sbphead);
	sendinfo(sockfd, send_buf, sizeof(send_buf));
	recinfo(sockfd);
	if (strcmp(rec_buf, "SBPFS_OK") == 0) {
		printf("succeed in report");
		return 0;
	} else if (strcmp(rec_buf, "SBPFS_ERR") == 0) {
		printf("fail in report");
		return -1;
	} else {
		perror("fail to receive feedback \n");
		return -1;
	}
}
/* Function:    rtsp_client_init
 * Description: Initialize the RTSP client
 * Parameters:  name - RTSP server name
 *              port - RTSP server port
 * Returns:     Success or failed
 */
rtsp_ret_e rtsp_client_init (const char *name, int port)
{
    rtsp_ret_e ret = RTSP_FAILURE;

    if (name != NULL) {
        strncpy(client.serverHost, name, MAX_NAME_LENGTH);
        client.serverPort = port;

        ret = ConnectServer(name, port);
        client.cSeq = 0;
        client.response.code = 0;
        client.response.server = NULL;
        client.response.data_buffer = NULL;
        client.response.body = NULL;
    }
    else {
        VQEC_LOG_ERROR("rtsp_client_init:: RTSP server name "
                        "or IP address must be specified\n");
    }

    return ret;
}
Example #29
0
//删除图片
void CDlgCustomFace::OnBnClickedDelete()
{
	//设置状态
	m_enOperateStatus = enOperateStatus_Delete;

	//链接网络
	if ( ConnectServer() == false )
	{
		//设置状态
		m_enOperateStatus = enOperateStatus_NULL;
		return;
	}

	//释放资源
	if ( ! m_Image.IsNull() ) m_Image.Destroy();

	//更新控件
	UpdateControls();

	//更新界面
	InvalidateRect(NULL);
}
TCGbool TCGClient::Init(TCGint argc, TCGchar **argv, const TCGchar* fname)
{
#ifdef Android
    if (!ParseArgFile(PLAY_CONF_FILE, g_args))
    {
        return ;
    }
#elif defined(WIN32) || defined(__APPLE__)
    if (!ParseArgv(argc, argv, g_args))
    {
        return TCG_FALSE;
    }
#endif

    GetScreenResolution();
    GetScreenPosition();
    ConnectServer();

    m_stream.SetCompressFlag(g_args.compressedFile);

    return TCG_TRUE;
}