Ejemplo n.º 1
0
void MainScreen::onIpPostButtonClickMessage(IpPostView* pSender, string ip, short post)
{
	if (pSender->getTag() == ID_LISTEN_VIEW)
	{
		if (m_pNetworkServer == NULL)
		{
			serverListen(ip.c_str(), post);
		}
		else
		{
			serverClose();
		}
	}
	else if (pSender->getTag() == ID_CONNECT_VIEW)
	{
		if (NetworkClient::sharedDelegate()->isConnected())
		{
			clientClose();
		}
		else
		{
			clientConnect(ip.c_str(), post);
		}
	}
}
Ejemplo n.º 2
0
int main(int argc, char *argv[])
{
    // Arguments parser.
    ClientArguments arguments;
    if (clientArgumentsCreate(&arguments, argc, argv) == ERROR) {
        return ERROR;
    }
    
    Client client;
    if (clientCreate(&client) == ERROR) {
        return ERROR;
    }
    
    char *url = clientArgumentsURL(&arguments);
    short port = clientArgumentsPort(&arguments);
    if (clientConnect(&client, url, port) == ERROR) {
        return ERROR;
    }
    
    if (clientReceive(&client) == ERROR) {
        return ERROR;
    }
    
    clientArgumentsDestroy(&arguments);
    clientDestroy(&client);
    
    return ZERO;
}
Ejemplo n.º 3
0
OOClient::OOClient(QString host, quint16 port, QObject* parent)
: QObject(parent),
 m_host(host),
 m_port(port),
 m_connected(false)
{
	connect(&m_client, SIGNAL(connected()), this, SLOT(clientConnect()));
	connect(&m_client, SIGNAL(disconnect()), this, SLOT(clientDisconnect()));
	//connect(&m_client, SIGNAL(error(QAbstractSocket::SocketError)), this, SLOT(errorHandler(QAbstractSocket::SocketError)));
	//connect(&m_client, SIGNAL(hostFound()), this, SLOT(hostFound()));
}
Ejemplo n.º 4
0
void TcpServer::incomingConnection(int handle)
{
    TcpClient *pClient = new TcpClient(this, handle);
    pClient->setSocketDescriptor(handle);
    connect(pClient, SIGNAL(clientReadData(int, QString, int, QByteArray)), \
            this, SIGNAL(clientReadData(int, QString, int, QByteArray)));
    connect(pClient, SIGNAL(clientDisConnect(int, QString, int)), \
            this, SLOT(disconnect(int, QString, int)));
    emit clientConnect(handle, pClient->peerAddress().toString(), pClient->peerPort());
    m_clientList.append(pClient);
    m_clientNum++;
}
EventMachineThread::EventMachineThread(QObject *parent) :
    QThread(parent)
{
    m_timeToReadData = new QTimer;
    m_server = new QTcpServer(this);

    if (!m_server->listen(QHostAddress::Any, PORT)) {
        qDebug() << "Fail open port " << PORT;
    }

    connect(m_server, SIGNAL(newConnection()), this, SLOT(clientConnect()));
}
Ejemplo n.º 6
0
//The `DataPacket` get deleted in the Session:receivePacket() method
void Player::handleDataPacket(RakLib::DataPacket* packet) {
	uint8 packetID = (*packet)[0];

	this->_server->getLogger()->debug("Packet ID: %02X", packetID);

	switch (packetID) {
	case MinecraftPackets::PING:
	{
		Ping ping(packet);
		ping.decode();


		Pong pong(ping.pingID);
		pong.encode();
		this->addToQueue(&pong, RakLib::Session::QueuePriority::IMMEDIATE);
	}
	break;

	case MinecraftPackets::CLIENT_CONNECT:
	{
		ClientConnect clientConnect(packet);
		clientConnect.decode();

		ServerHandshake serverHandshake(this->_ip, this->_port, clientConnect.sendPing, clientConnect.sendPing * 1000L);
		serverHandshake.encode();
		this->addToQueue(&serverHandshake, RakLib::Session::QueuePriority::IMMEDIATE);
	}
	break;

	case MinecraftPackets::LOGIN_PACKET:
	{
		Login login(packet);
		login.decode();

		if (login.protocol != NETWORK_PROTOCOL || login.protocol2 != NETWORK_PROTOCOL){
			if (login.protocol < NETWORK_PROTOCOL || login.protocol2 < NETWORK_PROTOCOL){
				//this->addToQueue(new LoginStatus(1)); // Client outdated
				//close("Wrong Protocol: Client is outdated.");
			}
			if (login.protocol > NETWORK_PROTOCOL || login.protocol2 > NETWORK_PROTOCOL){
				//addPacketToQueue(new LoginStatus(2)); // Server outdated
				//close("Wrong Protocol: Server is outdated.");
			}
		}

		this->_server->getLogger()->debug("%s (%s:%d) have joined...", login.username.c_str(), this->_ip.c_str(), this->_port);

		
	}
	break;

	}
}
int main( int argc, char *argv[] ) {
	clientSocket cSocket;
	destSpec dest;
	userOpts option = OPT_NOSELECTION;

	unsigned char data[MAXDATASIZE];
	size_t dataLen;

	//processInputParams( argc, argv, dest );

	dest.addr = "127.0.0.1";
	dest.port = "3000";

//	printf( "Here\n" );

	if( clientConnect( &cSocket, &dest ) == -1 ) {
		perror( "clientConnect" );
		return 1;
	}

//	printf( "Here2\n" );

	while( option != OPT_QUIT ) {
		//Do stuff
		if( option != OPT_NOSELECTION ) {
			if( clientSendOpt( &cSocket, option, data, dataLen ) == -1 ) {
				perror( "clientSendOpt" );
				return 1;
			}
		}

		if( option == OPT_RECV ) {
			if( clientWaitForFile( &cSocket, data, dataLen ) == -1 ) { //Wait for the server's response, store it in the filename still specified in data
				perror( "ClientWaitForFile Error" );
			}
		}

		if( queryUser( &option, data, MAXDATASIZE, &dataLen ) == -1 ) {
				perror( "queryUser" );
				return 1;
		}
	}

//	printf( "Here3\n" );

	clientSendOpt( &cSocket, option, NULL, 0 ); //Let the server know
	clientDisconnect( &cSocket );

	return 0;
}
Ejemplo n.º 8
0
void jus::Service::callBinary(uint32_t _transactionId, jus::Buffer& _obj) {
	if (_obj.getType() == jus::Buffer::typeMessage::event) {
		/*
		std::string event = _obj["event"].toString().get();
		if (event == "IS-ALIVE") {
			// Gateway just aswer a keep alive information ...
			// Nothing to do ...
		} else {
			JUS_ERROR("Unknow event: '" << event << "'");
		}
		*/
		JUS_ERROR("Unknow event: '...'");
		return;
	}
	if (_obj.getType() == jus::Buffer::typeMessage::answer) {
		JUS_ERROR("Local Answer: '...'");
		return;
	}
	//if (_obj.getType() == jus::Buffer::typeMessage::event) {
	uint32_t clientId = _obj.getClientId();
	std::string callFunction = _obj.getCall();
	if (callFunction[0] == '_') {
		if (callFunction == "_new") {
			std::string userName = _obj.getParameter<std::string>(0);
			std::string clientName = _obj.getParameter<std::string>(1);
			std::vector<std::string> clientGroup = _obj.getParameter<std::vector<std::string>>(2);
			clientConnect(clientId, userName, clientName, clientGroup);
		} else if (callFunction == "_delete") {
			clientDisconnect(clientId);
		}
		m_interfaceClient->answerValue(_transactionId, true, clientId);
		return;
	} else if (isFunctionAuthorized(clientId, callFunction) == true) {
		callBinary2(_transactionId, clientId, callFunction, _obj);
		return;
	} else {
		m_interfaceClient->answerError(_transactionId, "NOT-AUTHORIZED-FUNCTION", "", clientId);
		return;
	}
}
Ejemplo n.º 9
0
/*************************************TcpClient::clientInit*********************************************/
void TcpClient::clientInit(sockaddr_in addr, int pipereadId) {
	pthread_mutex_init(&(this->mutex), NULL); //初始化互斥锁
	this->setstatus(false); //初始后状态字
	this->pipewrite = pipereadId; //设置写管道ID
	debug("Child:pipewriteID:%d child's process pid:%d\n" ,this->pipewrite,getpid());

	this->clientsock = socket(AF_INET, SOCK_STREAM, 0);
	if (this->clientsock == -1) {
		cout << "create client error" << endl;
	}

	if (0 == clientConnect(addr, sizeof(sockaddr_in), CONNECTTIMEOUT)) {
		//正常连接,则创建发送线程
		pthread_create(&(this->tid), NULL, PerTransFun, (void *) this); //创建周期性发数据的线程
	} else {
		//处理硬错误,错误代码111,此时connect不会阻塞到SIGALRM信号的发生
		cout << "Client(" << getpid() << "):connect timeout within given time";
		perror("");
		exit(-1);
	}
	//创建select来接收到来的包,并调用函数进行分析
	fd_set rset;
	FD_ZERO(&rset);
	struct timeval tt;
	tt.tv_sec = 1;
	tt.tv_usec = 0;

	while (1) {
		FD_SET(this->clientsock, &rset);
		select((this->clientsock) + 1, &rset, NULL, NULL, &tt);
		if (this->getstatus() && FD_ISSET(this->clientsock,&rset)) {
			this->coordinate.push_back(recvdata());
		} else if (!this->getstatus()) {
			break;
		}
	}
	pthread_join(this->tid, NULL);
	debug("Child:init end child's process pid:%d\n" , getpid());
}
Ejemplo n.º 10
0
void RemoteConnection_updateListner(int currentRow)
{
	struct timeval timeout;
	struct sockaddr_in client;
	SOCKET clientSocket = INVALID_SOCKET;
	fd_set fds;

	FD_ZERO(&fds);
	FD_SET(s_serverSocket, &fds);

	timeout.tv_sec = 0;
	timeout.tv_usec = 0;
	
	if (RemoteConnection_connected())
		return;

	// look for new clients
	
	if (select(s_serverSocket + 1, &fds, NULL, NULL, &timeout) > 0)
	{
		clientSocket = clientConnect(s_serverSocket, &client);

		if (INVALID_SOCKET != clientSocket)
		{
			snprintf(s_connectionName, sizeof(s_connectionName), "Connected to %s", inet_ntoa(client.sin_addr));
			rlog(R_INFO, "%s\n", s_connectionName); 
			s_socket = clientSocket; 
			s_clientIndex = 0;
			RemoteConnection_sendPauseCommand(true);
			RemoteConnection_sendSetRowCommand(currentRow);
		}
		else 
		{
			//
		}
	}
}
Ejemplo n.º 11
0
int
main(int argc, char *argv[])
{
    int rc, infinite = 0, count=0;
    FDType serverFD;

    processArgs(argc, argv);

    if (server) {
        serverLoop();
        fprintf(stderr, "oops server loop terminated\n");
    }

    if (!host) {
	usage();
        fprintf(stderr, "sockTestSrv: FAIL: please use -h to specify host\n");
        return 1;
    }
    printf("host = %s\n", host);

    if (!port) {
        fprintf(stderr, "must specify server port with -p\n");
        return 0;
    }
    printf("port = %d\n", port);


    rc = 1;
    if (clientAction == CMD) {
        serverFD = clientConnect(host, port);
        if (serverFD == -1) return 0;
        rc = cmdClient(serverFD);
        close(serverFD);
    } else if (clientAction == ECHO) {
        if (repeatCount == 0) { infinite = 1; count = 0; }
        while (1) {
            if (!infinite && repeatCount==0) {
                break;
            }
            serverFD = clientConnect(host, port);
            if (serverFD == -1) return 0;
            rc = echoClient(serverFD);
            close(serverFD);
            if (!infinite) {
                repeatCount--;
                write(1,".",1);
                if (repeatCount) {
                    doDelay();
                }
            } else {
                count++;
                if (count == 1000) {  write(1,".",1); count=0; }
                doDelay();
            }
        }
    } else {
        fprintf(stderr, "unknown client action\n");
        rc = 0;
    }
    return rc;
}
Ejemplo n.º 12
0
Archivo: client.cpp Proyecto: Try/game
void Client::connect(const std::string &addr) {
  connection.join();
  clientConnect( addr.data() );
  }
Ejemplo n.º 13
0
/**
 * Author: 	 	Joel Denke, Marcus Isaksson
 * Description:		Run the game on client
 */
int main(int argc, char *argv[])
{
	int i, j, no, yb, keysHeld[323] = {0};
	int result = 0;
	SDL_Thread * eventBuffer;
	SDL_Thread * runBuffer;
	struct timer_t2 fps;
	
	char * server_ip = malloc(sizeof(char) * 16);
	char * elem = malloc(sizeof(char) * MESSAGE_SIZE);

	pColor = malloc(sizeof(SDL_Color));
	oColor = malloc(sizeof(SDL_Color));
	connection = malloc(sizeof(connection_data));

	for (i = 0; i < NO_BUFFERS; i++) {
		cb[i] = malloc(sizeof(cBuffer));
		b_lock[i] = SDL_CreateMutex();
	}

	strcpy(server_ip, "127.0.0.1");

	pColor->r = 0;
	pColor->g = 255;
	pColor->b = 255;
	oColor->r = 0;
	oColor->g = 0;
	oColor->b = 255;

	initGraphics();
	initSound();

	printf("Render menu\n");
	graphicsMenu(&gameWorld, server_ip);

	initSlots(cb[0], BUFFER_SIZE);
	initSlots(cb[1], NO_OBJECTS);
	initSlots(cb[2], BUFFER_SIZE);

	state = gStart;

	if (clientConnect(connection, server_ip) == 0)
	{
		eventBuffer = SDL_CreateThread(listenEventBuffer, &connection);

		while (1) {
			switch (state) {
				case gStart:
					runData(2);
					break;
				case gInit:
					timer_start(&fps);
					startDraw();
					drawLoadScr(SCREEN_WIDTH, SCREEN_HEIGHT);
					endDraw();

					initWorld();
					
					if (timer_get_ticks(&fps) < 1000 / FPS)
					{
						//delay the as much time as we need to get desired frames per second
						SDL_Delay( ( 1000 / FPS ) - timer_get_ticks(&fps) );
					}
					break;
				case gRunning :
					timer_start(&fps);
					drawGraphics();
					listenInput(keysHeld);

					// i = 0: players; i = 1: objects; i = 2: messages
					for (i = 0; i < NO_BUFFERS; i++) {
						runData(i);
					}

					if (timer_get_ticks(&fps) < 1000 / FPS)
					{
						//delay the as much time as we need to get desired frames per second
						SDL_Delay( ( 1000 / FPS ) - timer_get_ticks(&fps) );
					}

					break;
				case gExit :
					//sprintf(string, "%d,quit", connection->client_id);
					printf("Freeing music now\n");
					pauseMusic();
					freeMusic();
					end_session(connection);
					printf("Player is exit game now\n");
					exitClient(eventBuffer);
					break;
				default :
					printf("test\n");
					break;
			}
		}
	} else {
		printf("Misslyckade med att kontakta servern på ip-adress: '%s'\n", server_ip);
		state = gExit;
		pauseMusic();
		freeMusic();
		exitClient(eventBuffer);
	}

	return 0;
}
Ejemplo n.º 14
0
int APIENTRY WinMain(HINSTANCE hInstance, HINSTANCE /*hPrevInstance*/,
    LPSTR /*lpCmdLine*/, int /*nShowCmd*/)
{
#ifdef _DEBUG
	_CrtSetDbgFlag(_CRTDBG_ALLOC_MEM_DF | _CRTDBG_LEAK_CHECK_DF);
/*	_CrtSetReportMode(_CRT_WARN, _CRTDBG_MODE_DEBUG);
	_CrtSetReportMode(_CRT_ERROR, _CRTDBG_MODE_DEBUG);
	_CrtSetReportMode(_CRT_ASSERT, _CRTDBG_MODE_DEBUG); */
//	_CrtSetBreakAlloc(254);
#endif
	
	hInst = hInstance;
	CoInitialize(NULL);

	WSADATA wsa;
	if (0 != WSAStartup(MAKEWORD(2, 0), &wsa))
		die("Failed to init network");

	SOCKET serverSocket = socket(AF_INET, SOCK_STREAM, 0);

	struct sockaddr_in sin;
	memset(&sin, 0, sizeof sin);

	sin.sin_family = AF_INET;
	sin.sin_addr.s_addr = INADDR_ANY;
	sin.sin_port = htons(1338);

	if (SOCKET_ERROR == bind(serverSocket, (struct sockaddr *)&sin,
	    sizeof(sin)))
		die("Could not start server");

	while (listen(serverSocket, SOMAXCONN) == SOCKET_ERROR)
		; /* nothing */

	ATOM mainClass      = registerMainWindowClass(hInstance);
	ATOM trackViewClass = registerTrackViewWindowClass(hInstance);
	if (!mainClass || !trackViewClass)
		die("Window Registration Failed!");

	trackView = new TrackView();
	trackView->setDocument(&document);
	
	hwnd = CreateWindowExW(
		0,
		mainWindowClassName,
		mainWindowTitleW,
		WS_OVERLAPPEDWINDOW | WS_CLIPCHILDREN,
		CW_USEDEFAULT, CW_USEDEFAULT, // x, y
		CW_USEDEFAULT, CW_USEDEFAULT, // width, height
		NULL, NULL, hInstance, NULL
	);

	if (NULL == hwnd)
		die("Window Creation Failed!");

	fileNew();
	
	HACCEL accel = LoadAccelerators(hInstance, MAKEINTRESOURCE(IDR_ACCELERATOR));
	
	ShowWindow(hwnd, TRUE);
	UpdateWindow(hwnd);
	
	bool done = false;
	MSG msg;
	bool guiConnected = false;
	while (!done)
	{
		if (!document.clientSocket.connected())
		{
			SOCKET clientSocket = INVALID_SOCKET;
			fd_set fds;
			FD_ZERO(&fds);
#pragma warning(suppress: 4127)
			FD_SET(serverSocket, &fds);
			struct timeval timeout;
			timeout.tv_sec = 0;
			timeout.tv_usec = 0;
			
			// look for new clients
			if (select(0, &fds, NULL, NULL, &timeout) > 0)
			{
				SendMessage(statusBarWin, SB_SETTEXT, 0, (LPARAM)"Accepting...");
				sockaddr_in client;
				clientSocket = clientConnect(serverSocket, &client);
				if (INVALID_SOCKET != clientSocket)
				{
					char temp[256];
					snprintf(temp, 256, "Connected to %s", inet_ntoa(client.sin_addr));
					SendMessage(statusBarWin, SB_SETTEXT, 0, (LPARAM)temp);
					document.clientSocket = NetworkSocket(clientSocket);
					document.clientRemap.clear();
					document.sendPauseCommand(true);
					document.sendSetRowCommand(trackView->getEditRow());
					guiConnected = true;
				}
				else SendMessage(statusBarWin, SB_SETTEXT, 0, (LPARAM)"Not Connected.");
			}
		}
		
		if (document.clientSocket.connected())
		{
			NetworkSocket &clientSocket = document.clientSocket;
			
			// look for new commands
			while (clientSocket.pollRead())
				processCommand(clientSocket);
		}
		
		if (!document.clientSocket.connected() && guiConnected)
		{
			document.clientPaused = true;
			InvalidateRect(trackViewWin, NULL, FALSE);
			SendMessage(statusBarWin, SB_SETTEXT, 0, (LPARAM)"Not Connected.");
			guiConnected = false;
		}
		
		while (PeekMessage(&msg, NULL, 0, 0, PM_REMOVE))
		{
			if (!TranslateAccelerator(hwnd, accel, &msg))
			{
				TranslateMessage(&msg);
				DispatchMessage(&msg);
				if (WM_QUIT == msg.message) done = true;
			}
		}
		Sleep(1);
	}

	closesocket(serverSocket);
	WSACleanup();

	delete trackView;
	trackView = NULL;

	UnregisterClassW(mainWindowClassName, hInstance);
	return int(msg.wParam);
}
Ejemplo n.º 15
0
int main(void)
{
	
    WatchDogDisable();

    NutDelay(100);

    SysInitIO();
	
	SPIinit();
    
	LedInit();
	
	LcdLowLevelInit();
	LcdBackLight(1);
	PrintStr("Starting System");
    Uart0DriverInit();
    Uart0DriverStart();
	LogInit();

    CardInit();

	char custom[48] = ALL;
	
	LoadCustomChars(custom, 6);
	
    X12Init();
    if (X12RtcGetClock(&gmt) == 0)
    {
		LogMsg_P(LOG_INFO, PSTR("RTC time [%02d:%02d:%02d]"), gmt.tm_hour, gmt.tm_min, gmt.tm_sec );
    }

    if (At45dbInit()==AT45DB041B)
    {
        // ......
    }


    RcInit();
    
	KbInit();

    SysControlMainBeat(ON);             // enable 4.4 msecs hartbeat interrupt
	
	ClearLcdScreen();

	//Nieuwe threads aanmaken
    NutThreadCreate("t01", Thread1, NULL, 512);
	NutThreadCreate("time", TimeUpdater, NULL, 512);
	
	//Start netwerk
	int i = initNetworkDHCP();
	LogMsg_P(LOG_INFO, PSTR("Ethernet Startup Message: [%d]"),i);

	//Haal Internet tijd op
	pgmt = getNTPTime();
	X12RtcSetClock(&pgmt);
	//LogMsg_P(LOG_INFO, PSTR("New RTC time [%02d:%02d:%02d]"), gmt.tm_hour, gmt.tm_min, gmt.tm_sec );

    /*
     * Increase our priority so we can feed the watchdog.
     */
    NutThreadSetPriority(1);

	/* Enable global interrupts */
	sei();

	/******************NETWERK**TEST*****************************************************/

	//Maak nieuwe socket
	TCPSOCKET *sock;
	sock = NutTcpCreateSocket();
	//Connect met google.nl
	LogMsg_P(LOG_INFO, PSTR("Connecting client"));
	clientConnect(sock);
	//Zend http req
	clientSend(sock,buffer,sizeof(buffer));

	//Ontvang response in buffer --> grotere buffer (1500)= crash-->heapsize??(8k ram)
	char rcvbuffer [500];
	int rec;
	rec = clientReceive(sock,rcvbuffer,sizeof(rcvbuffer));
	LogMsg_P(LOG_INFO, PSTR("received [%d]"),rec);

	//0 terminate buffer(string)
	//rcvbuffer[499] = 0;

	//Print buffer(http response enz)
	LogMsg_P(LOG_INFO, PSTR("received [%s]"),rcvbuffer);
	
	//Sluit connectie
	clientClose(sock);
	/***********************************************************************************/

	//Main gui besturing??
    for (;;)
    {
        NutSleep(100);
        WatchDogRestart();
    }

    return(0);      
}
Ejemplo n.º 16
0
int main(int argc, char *argv[])
{
	char *servhost = (char *)HOST;
	long port = PORT;
	unsigned long numOfBlocks = 0;
  int flag = 1;
	if (argc >= 2)
	{
		if (isalpha(argv[1][0]) || argv[1][0] == '?')
		{
			cout << "pclient [numOfBlocks = 10] [numOfChallenges=50] [Server Name = localhost] [Port = 8888]" << endl;
			exit(0);
		}
		else if(argv[1][0] == '-')
      flag= 0;
    else
			numOfBlocks = atoi(argv[1]);
	}

	int numOfChallenges = CHALLNUM;
  if (argc >=3)
    numOfChallenges = atoi(argv[2]); 
	if (argc >=4)
		servhost = argv[3];
	if (argc >= 5)
		if (atoi(argv[4]) > 1024)
			port = atoi(argv[4]);

	/* no of challenges in the challenge set */
    unsigned l;                        		

    unsigned long indexSize = getPrimeKeys();
    if (numOfBlocks > 0 && numOfBlocks<indexSize)
    	l = numOfBlocks;
    else
    	l = BLOCKNUM;

	int sock = clientConnect(servhost, port);
  doHandshake(numOfChallenges, flag, sock);
  FILE *foutput = prepareOutput(servhost, l, flag);

	char output[1024] = {0};
	bool res = false;
	uint64_t elapsed = 0;
	for (int i=0; i<numOfChallenges; i++)
	{
    elapsed = 0;
    if (flag)
		  res = challengeResponse(sock, l, &elapsed);
    else
      res=FileRet(sock, &elapsed);

		if (res)
			snprintf(output, 15, "%s", "Data Verified");
		else
			snprintf(output, 15, "%s", "Data lost");
		fprintf(foutput, "%llu \t\t\t %s \n", elapsed, output);
		//write the results
	}

	fclose(foutput);
	closeSocket(sock);
	return 0;	
}
Ejemplo n.º 17
0
int clientConnect(int argc, char **argv)
{
	hostent 	*ptr_client;			/* Client infos */
	hostent 	*ptr_host;				/* Host infos */
	char 		*prog;					/* Program Name */
	const char 	*hostc;					/* Server address char* */
	in_addr		host;					/* Server address */
	char 		login[LOGIN_SIZE];		/* User name */
	char 		pass[PASSWORD_MAX];		/* User password */
	int 		port;					/* Port of the remote machine */
	bool linked =		False;			/* If the linbk with server is etablished */
	int try =			1;				/* Number of connecting try */
	int try_Max =		MAX_CONNECTION_TRY;	/* Maximum of try to connect */
	int askCo =			0;				/* Result of the connection try */
	STATE =				False;			/* Set client status to disconnected */
	int errorN =		0;				/* Error numlber */
	struct timeval timeout;				/* Timeout for read and write */
	timeout.tv_sec =	RS_TIMEOUT;
	timeout.tv_usec =	0;
	
	if (argc < 5)
	{
		if(argc>0)
		{
			prog = argv[0];
		}
		else
		{
			prog = "client";
		}
		sprintf(logC,"%s <server_address> <server_port> <user_name> <user_password>\n",prog);
		consoleUsage(logC);
		memset(&logC,0,strlen(logC));
		exit(1);
	}
	
	prog = argv[0];
	hostc = argv[1];
	inet_aton(hostc, &host);
	
	port = atoi(argv[2]);
	strcpy(login,argv[3]);

	if (strlen(login) > (LOGIN_SIZE-1)){   // 'Cause of '\0'
		/* Error 13: Login size too long (17 char max) */
		consoleErrorLog(13);
		exit(1);
	}
	
	strcpy(pass,argv[4]);
	
	if (strlen(pass) > (PASSWORD_MAX-1) || strlen(pass) < (PASSWORD_MIN)){   // 'Cause of '\0'
  		/* Error 14: Password size incorrect (Between 7 and 19) */
		consoleErrorLog(14);
		exit(1);
	}

	int argN = 5;
	/* while(argN<argc)
	{
		char tmp[strlen(msg)+strlen(argv[argN])+1];
		strcpy(tmp,msg);
		strcat(tmp," ");
		strcat(tmp,argv[argN]);
		strcpy(msg,tmp);
		argN++;
	} */
	
	char machine[NAME_SIZE+1];
	
	gethostname(machine,NAME_SIZE);
	if((ptr_client = gethostbyname(machine)) == NULL)
	{
		consoleError("Can not find the machine address");
		return errno;
	}
	
	/* character by character copy of ptr_client informations to client address */
	bcopy((char*)ptr_client->h_addr, (char*)&client_address.sin_addr,ptr_client->h_length);
	client_address.sin_family = AF_INET;
	
	/* Use a new port number */
	client_address.sin_port = htons(port);
	
	if((ptr_host = gethostbyname(hostc)) == NULL)
	{
		consoleError("Can not find the server from its address");
		return errno;
	}
	
	/* character by character copy of ptr_host informations to local address */
	bcopy((char*)ptr_host->h_addr, (char*)&server_address.sin_addr,ptr_host->h_length);
	server_address.sin_family = AF_INET;
	
	/* Use a new port number */
	server_address.sin_port = htons(port);
	
	/* Creation of the socket */
	if ((socket_descriptor = socket(AF_INET, SOCK_STREAM, 0)) <0){
		consoleError("Unable to create socket connection with the server");
		return errno;
	}
	
	if (setsockopt (socket_descriptor, SOL_SOCKET, SO_RCVTIMEO, (char *)&timeout,
				sizeof(timeout)) < 0)
	{
		consoleWarn("Set socket receive options failed\n");
	}

	if (setsockopt (socket_descriptor, SOL_SOCKET, SO_SNDTIMEO, (char *)&timeout,
				sizeof(timeout)) < 0)
	{
		consoleWarn("Set socket send options failed\n");
	}
	
	while(!STATE&&try<=try_Max)
	{
		/* Try to connect to the server with infos in server_address */
		if(!linked&&(connect(socket_descriptor, (sockaddr*)(&server_address), sizeof(sockaddr_in))) < 0)
		{
			consoleError("Unable to connect to server");
			errorN=errno;
		}
		else
		{
			if(!linked)
			{
				consoleLog("Connection established with the server\n");
				errorN=0;
			}
			linked=True;
			askCo=askConnection(server_address.sin_addr,login,pass,SERVER_ADMIN_NAME);
			if(askCo==0&&STATE)
			{
				try=0;
			}
			else
			{
				/* Server is full, we can try until someone disconnect */
				if(askCo==0)
				{
					try_Max=100;
				}
				else
				{
					// Wrong password || Login not allowed || Login already used
					if(askCo==3||askCo==2||askCo==1)
					{
						exit(0);
					}
					try_Max=MAX_CONNECTION_TRY;
				}
			}
		}
		if(!STATE)
		{
			sprintf(errorC,"Attempt (#%d) to connect to server failed [with error #%d]\n",try++,askCo);
			consoleError(errorC);
			memset(&errorC,0,strlen(errorC));
			if(askCo==14||askCo==22)
			{
				errorN=askCo;
				close(socket_descriptor);
				return clientConnect(argc,argv);
			}
			if(try<try_Max)
			{
				consoleLog("Retry to connect in 3 seconds...\n");
				sleep(3);
			}
		}
bool connectSrv(char *param, void *conf)
{
    clientConfig *c=(clientConfig*)conf;
    clientConnect(c);
    return true;
}