Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- //connect to the server
- iResult = connect(client, (sockaddr*)&server, sizeof(server));
- if(iResult == SOCKET_ERROR)
- {
- iError = WSAGetLastError();
- //check if error was WSAEWOULDBLOCK, where we'll wait
- if(iError == WSAEWOULDBLOCK)
- {
- cout << "Attempting to connect.\n";
- fd_set Write, Err;
- TIMEVAL Timeout;
- int TimeoutSec = 10; // timeout after 10 seconds
- FD_ZERO(&Write);
- FD_ZERO(&Err);
- FD_SET(client, &Write);
- FD_SET(client, &Err);
- Timeout.tv_sec = TimeoutSec;
- Timeout.tv_usec = 0;
- iResult = select(0, //ignored
- NULL, //read
- &Write, //Write Check
- &Err, //Error Check
- &Timeout);
- if(iResult == 0)
- {
- cout << "Connect Timeout (" << TimeoutSec << " Sec).\n";
- system("pause");
- return 1;
- }
- else
- {
- if(FD_ISSET(client, &Write))
- {
- cout << "Connected!\n";
- }
- if(FD_ISSET(client, &Err))
- {
- cout << "Select error.\n";
- system("pause");
- return 1;
- }
- }
- }
- else
- {
- cout << "Failed to connect to server.\n";
- cout << "Error: " << WSAGetLastError() << endl;
- WSACleanup();
- system("pause");
- return 1;
- }
- }
- else
- {
- //connected without waiting (will never execute)
- cout << "Connected!\n";
- }
- ///////////////////////
- bool connect(char *host,int port, int timeout)
- {
- TIMEVAL Timeout;
- Timeout.tv_sec = timeout;
- Timeout.tv_usec = 0;
- struct sockaddr_in address; /* the libc network address data structure */
- sock = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
- address.sin_addr.s_addr = inet_addr(host); /* assign the address */
- address.sin_port = htons(port); /* translate int2port num */
- address.sin_family = AF_INET;
- //set the socket in non-blocking
- unsigned long iMode = 1;
- int iResult = ioctlsocket(sock, FIONBIO, &iMode);
- if (iResult != NO_ERROR)
- {
- printf("ioctlsocket failed with error: %ld\n", iResult);
- }
- if(connect(sock,(struct sockaddr *)&address,sizeof(address))==false)
- {
- return false;
- }
- // restart the socket mode
- iMode = 0;
- iResult = ioctlsocket(sock, FIONBIO, &iMode);
- if (iResult != NO_ERROR)
- {
- printf("ioctlsocket failed with error: %ld\n", iResult);
- }
- fd_set Write, Err;
- FD_ZERO(&Write);
- FD_ZERO(&Err);
- FD_SET(sock, &Write);
- FD_SET(sock, &Err);
- // check if the socket is ready
- select(0,NULL,&Write,&Err,&Timeout);
- if(FD_ISSET(sock, &Write))
- {
- return true;
- }
- return false;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement