| |||||||||
![]() |
|
|
«
Previous Thread
|
Next Thread
»
|
Thread Tools | Search this Thread | Display Modes |
|
#1
|
|||
|
|||
|
Hi again,
Lately I'm doing socket programming, as far I can tell it works fine. the problem is that how do I know if a server (on the box) is running. The gethostbyname() will only detect if a IP address exist or is currently running. The only idea that I have is, after gethostbyname() and a successful connect() my program will send some sort of message, then the (workspace)server will then send a valid response. If no valid response is recieve then the process will start all over again. is this the way to go, just to know if a (workspace)server is running or there is another way ? regards, jaro |
|
#2
|
|||
|
|||
|
well, if you can connect() to a server, it is running. If by "server" you mean a specific program, not the whole machine, then some kind of confirmation message (using a GUID or a password or something) is probably the best way to go.
|
|
#3
|
|||
|
|||
|
Quote:
Now what if, while the program is still connected to the server and by some wierd reason the server shuts down (i.e. power outage), how would I know if the server is still running? I'm thinking of doing a connect() from time to time to check if the connection is still fine.If connect() returns other than "socket is still connected" (WSAEISCONN) then the program will try to reconnect and will continue to do so until it is connected again. is this the logical way to go? or there is another way ? |
|
#4
|
|||
|
|||
|
Well presumably if you are maintaining the socket you are send()ing and recv()ing with it, and you know to stop using it when those return an error code indicating a broken connection like WSAEINTR (has been closed), WSAENOTCONN (not connected), WSAENETRESET (kepp-alive service failed and broke connection), WSAESHUTDOWN (the socket was shutdown() peacefully), WSAECONNABORTED (something died and the connection was broken), WSAETIMEDOUT (the network died or the other computer stopped responding), or WSAECONNRESET (something died on the remote computer and broke the connection).
If you are not regularly reading or writing to the socket (but then what would be the point of maintaining the connection) then the connect() approach might be best. You could also use select() and put your socket in the list of sockets to check for errors (for this approach you'd probably also want to make that call to select() nonblocking). HTH, ubergeek |
|
#5
|
|||
|
|||
|
Ok.I realize that doing a connect() from time to time to check if the connection is not really the way to go and also waste resources.
I did some changes in the codes ,following ubergeek advice,and the result is written below. Also ubergeek advice to use select(),but these pass weeks I have been busy and I haven't read yet on how to use select(). Code:
#include <stdio.h>
#include <winsock.h>
#define STRSIZE 16536
void handle_error(void);
void receiveMessage(void);
void connectToWorkSpace();
char recvbuf[60000] = "";
SOCKET ConnectSocket;
struct sockaddr_in clientService;
int bytesSent;
int bytesRecv = 0;
char sendbuf[500] = "";
struct hostent *h;
char HOSTNME[20]="";
char hostname[20] = "localhost"; // for testing purposes
char hostnamebackup[20] = "local-blahblah"; // for testing purposes
int chker=0;
int main()
{
connectToWorkSpace();
while(1){
receiveMessage();
}
}
void receiveMessage()
{
int bytesRecv = 0;
bytesRecv = recv( ConnectSocket, recvbuf, 60000, 0 );
if (bytesRecv == 0 ||
bytesRecv == SOCKET_ERROR ||
WSAGetLastError() == WSAEINTR || /*(has been closed)*/
WSAGetLastError() == WSAENOTCONN || /*(not connected)*/
WSAGetLastError() == WSAENETRESET || /*(kepp-alive service failed and broke connection)*/
WSAGetLastError() == WSAESHUTDOWN || /*(the socket was shutdown() peacefully)*/
WSAGetLastError() == WSAECONNABORTED || /*(something died and the connection was broken)*/
WSAGetLastError() == WSAETIMEDOUT || /*(the network died or the other computer stopped responding)*/
WSAGetLastError() == WSAECONNRESET /*(something died on the remote computer and broke the connection)*/
){
printf("Reconnect!\n");
connectToWorkSpace();
}else{
recvbuf[bytesRecv]='\0';
if(strlen(recvbuf)>0){
printf("received message: %s \n", recvbuf);
}
}
}
void connectToWorkSpace()
{
int chkHost=0;
int loopHost=0;
int conn = 1;
WSADATA wsaData;
WORD wVersionRequested;
wVersionRequested = MAKEWORD( 1, 1 );
if ( WSAStartup( wVersionRequested, &wsaData ) != 0 ){
fprintf(stderr,"WSAStartup Error...");
handle_error();
}
// will loop until connect() is successful
while(conn != 0){
chkHost =chker%2;
if(chkHost == 0){
printf("Connect Using Primary Host\n");
strcpy(HOSTNME,hostname);
}
else {
printf("Connect Using Backup Host\n");
strcpy(HOSTNME,hostnamebackup);
}
// will loop until HOSTNME is reachable
while(loopHost==0){
chkHost =chker%2;
if((h=gethostbyname(HOSTNME))==NULL)
{
printf("%s not reachable\n",HOSTNME);
if(chkHost == 1){
printf("Connect Using Primary Host\n");
strcpy(HOSTNME,hostname);
}
else {
printf("Connect Using Backup Host\n");
strcpy(HOSTNME,hostnamebackup);
}
}else{
loopHost=1;
}
Sleep(1000);
chker++;
}
clientService.sin_addr=*((struct in_addr*)h->h_addr);
clientService.sin_port = htons(8770);
clientService.sin_family = AF_INET;
// Create a SOCKET for connecting to server
ConnectSocket = socket(AF_INET, SOCK_STREAM, 0);
if (ConnectSocket == -1) {
handle_error();
printf("Error at socket(): \n");
//return -1;
}
// Connect
if( connect( ConnectSocket, (struct sockaddr*) &clientService, sizeof(struct sockaddr) ) == -1) {
printf("Failed to connect. Workspaceserver is down.\n" );
printf("Reconnecting........\n" );
loopHost=0;
Sleep(5000);
conn = 1;
}
else {
conn = 0;
printf("Connection Success!\n");
}
}
strcpy(sendbuf,"jaro");
strcat(sendbuf, " :username");
strcat(sendbuf, "\n");
/* Send */
bytesSent = send( ConnectSocket, sendbuf, strlen(sendbuf), 0 );
printf( "\n messages Sent: %s\n", sendbuf );
}
void handle_error(void)
{
/*
* Errors are handled by calling the WSAGetLastError routine which
* will return the last error as one of the following. As we develop
* this tutorial, we will go into much more detail on what they mean
* and what caused them.
*/
int x;
x= WSAGetLastError();
switch ( x )
{
case WSANOTINITIALISED :
printf("Unable to initialise socket.\n");
break;
case WSAEAFNOSUPPORT :
printf("The specified address family is not supported.\n");
break;
case WSAEADDRNOTAVAIL :
printf("Specified address is not available from the local machine.\n");
break;
case WSAECONNREFUSED :
printf("The attempt to connect was forcefully rejected.\n");
break;
case WSAEDESTADDRREQ :
printf("address destination address is required.\n");
break;
case WSAEFAULT :
printf("The namelen argument is incorrect.\n");
break;
case WSAEINVAL :
printf("The socket is not already bound to an address.\n");
break;
case WSAEISCONN :
printf("The socket is already connected.\n");
break;
case WSAEADDRINUSE :
printf("The specified address is already in use.\n");
break;
case WSAEMFILE :
printf("No more file descriptors are available.\n");
break;
case WSAENOBUFS :
printf("No buffer space available. The socket cannot be created.\n");
break;
case WSAEPROTONOSUPPORT :
printf("The specified protocol is not supported.\n");
break;
case WSAEPROTOTYPE :
printf("The specified protocol is the wrong type for this socket.\n");
break;
case WSAENETUNREACH :
printf("The network can't be reached from this host at this time.\n");
break;
case WSAENOTSOCK :
printf("The descriptor is not a socket.\n");
break;
case WSAETIMEDOUT :
printf("Attempt timed out without establishing a connection.\n");
break;
case WSAESOCKTNOSUPPORT :
printf("Socket type is not supported in this address family.\n");
break;
case WSAENETDOWN :
printf("Network subsystem failure.\n");
break;
case WSAHOST_NOT_FOUND :
printf("Authoritative Answer Host not found.\n");
break;
case WSATRY_AGAIN :
printf("Non-Authoritative Host not found or SERVERFAIL.\n");
break;
case WSANO_RECOVERY :
printf("Non recoverable errors, FORMERR, REFUSED, NOTIMP.\n");
break;
case WSANO_DATA :
printf("Valid name, no data record of requested type.\n");
break;
case WSAEINPROGRESS :
printf("address blocking Windows Sockets operation is in progress.\n");
break;
case WSAEINTR :
printf("The (blocking) call was canceled via WSACancelBlockingCall().\n");
break;
default :
printf("Unknown error.\n");
break;
}
}
Just need some comment (good or bad) on the program that I've written. Just need to know if I'm on the right track. regards, jaro |
|
#6
|
|||
|
|||
|
looks pretty good. Just one thing, in the receiveMessage function, you might want to call WSAGetLastError() once and store the result in a variable, then compare against the variable, to avoid the overhead of calling the API function so many times.
|
![]() |
| Viewing: Dev Articles Community Forums > Programming > C/C++ Help > How do I know if a server (on the box) is running? |
| Thread Tools | Search this Thread |
| Display Modes | Rate This Thread |
|
|
|
|
|