【转】select+TCP/IP 实例片段(供参考)

转自:http://aea.web.psi.ch/Urs_Rohrer/MyWeb/sample1.htm

 

The following program prints onto the screen a list of the DAC and ADC values of all devices (command = RALL) of a given beam line. You may run this program test by  entering the command 'test Server_Name Port_ID'. It is also possible to redirect the generateded output list to a file by appending a third parameter to the command line [ >File_Name ].

 

 

/*=====================================================
  |  Demo program for remote CAMAC access via TCP/IP  |
  =====================================================*/

#ifdef WIN32
#include <windows.h>
#include <process.h>
#include <stddef.h>
#include <stdlib.h>
#include <winsock.h>
#include <stdarg.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <memory.h>
#include <time.h>
#include <ctype.h>
#include <io.h>
#include <share.h>
#include <fcntl.h>
#include <sys\stat.h>
#else  /* Unix */
#include <sys/types.h>
#include <sys/socket.h>
#include <sys/shm.h>
#include <netinet/in.h>
#include <netdb.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <errno.h>
#include <time.h>
#include <pthread.h>
#include <ctype.h>
#include <unistd.h>
#include <fcntl.h>
#include <sys/stat.h>
#include <sys/ioctl.h>
#endif

#define	MAXLEN	    2048	/* max command buffer length */
#define	BACKLOG	    5		/* max outstanding connections	*/
#define	FLAGS	    0		/* flags argument, must be zero	*/
#ifdef WIN32
#define errno WSAGetLastError()
#else
#define closesocket close
#define SOCKET int
#endif

SOCKET	l_socket;

int DataTransfer(char *command_s, char *r_buffer)
{
   int	   count, z, status;
   struct  timeval timeout;
   fd_set  readfds;
   int     msecs = 4000;

   count = send ( l_socket, command_s, strlen(command_s) + 1, FLAGS ); // zero-terminated
   if ( count == -1)
   {
        printf ("** Error sending data **\n");
        return 0;
   }

   z = 0;
   while(1)
   {
      if (msecs > 0)
      {
	 FD_ZERO(&readfds);
	 FD_SET(l_socket,&readfds);
	 timeout.tv_sec  = msecs / 1000;
	 timeout.tv_usec = (msecs % 1000) * 1000;
	 status = select(FD_SETSIZE, &readfds, NULL, NULL, &timeout);
	 if (status == -1)
	 {
            printf ("** Error while selecting **\n");
	    return 0;
	 }
	 if (!FD_ISSET(l_socket,&readfds))
	 {
	    printf ("** Timeout while selecting **\n");
	    r_buffer[z] = '\0';  // terminate it by adding a '\0'
	    z++;
	    break;
	 }
      }

      count = recv ( l_socket, &r_buffer[z], MAXLEN, FLAGS );
      if ( count == -1 )
      {
         printf ("** Error receiving answer **\n");
         return 0;
      }
      else
         z += count;

      if (r_buffer[z-1] == '\0')  // termination has arrived
	 break;
   }

   return z;
}

void Display(void)
{
    char buffer[MAXLEN];
    char command[MAXLEN];

    sprintf(command,"RALL");
    DataTransfer(command,buffer);

    /* reservation ok */

    if ( buffer[7] != '0' )
    {
        printf("%s\n",&buffer[6]);
    }
}

int main (int argc, char *argv[])
{
   int	status;
   int	shutdown_required = 0;
   char	localhost_s[20];
   char	remothost_s[20];

   struct  sockaddr_in	l_socket_s;
   struct  sockaddr_in	r_socket_s;

   struct  hostent *localhost_p;
   struct  hostent *remothost_p;

   unsigned long non_blocking = 1 ;
   unsigned long blocking = 0 ;
   struct  timeval timeout;
   fd_set  readfds, writefds;
   int     msecs = 4000;
   int     error=0, len;

#ifdef WIN32
   WORD    wVersionRequested;
   WSADATA wsaData;
   int     err;
#else
   typedef struct sockaddr *LPSOCKADDR;
#endif

    /* Check argument list length */

    if (argc != 3)
    {
        printf("Usage: client Servername ServerPort\n");
        exit(1);
    }

    /*  Start WinSocket-DLL  */

#ifdef WIN32
    wVersionRequested = MAKEWORD(1,1);
    err = WSAStartup(wVersionRequested,&wsaData);
    if (err != 0)
    {
	printf ("** WinSocket-DLL not found **\n");
	exit(1);
    }
#endif

    /*	Create a socket  */

    l_socket	=   socket ( AF_INET, SOCK_STREAM, 0 );
    if ( l_socket == -1 )
    {
	printf ("** Error Creating Socket **\n");
	exit(1);
    }

    /*	Get hostname  */

    gethostname(localhost_s,sizeof(localhost_s));
    localhost_p   =   gethostbyname ( localhost_s );
    if ( localhost_p == NULL )
    {
        printf ("** Cannot get hostaddress of %s **\n",localhost_s);
        exit(1);
    }

    /*	bind socket to port  */
    
    l_socket_s.sin_family	=   AF_INET;
    l_socket_s.sin_port		=   htons ( 0 );
    l_socket_s.sin_addr.s_addr	=   0;
    memcpy((char*)&(l_socket_s.sin_addr), localhost_p->h_addr, localhost_p->h_length);

    status = bind ( l_socket, (LPSOCKADDR)&l_socket_s, sizeof(l_socket_s));

    if ( status == -1 )
    {
	printf ("** Error Binding Socket, errno = %d **\n",errno);
        shutdown ( l_socket , 2 );
	exit(1);
    }

    /*	Get Server name  */

    strcpy(remothost_s,argv[1]);
    remothost_p   =   gethostbyname ( remothost_s );
    if ( remothost_p == NULL )
    {
        printf ("** Cannot get remote address %s **\n", remothost_s);
        exit(1);
    }

    /*  Connect to Server socket  */

    r_socket_s.sin_family	=   AF_INET;
    r_socket_s.sin_port		=   htons ( (unsigned short)atol(argv[2]) );
    r_socket_s.sin_addr.s_addr	=   *(unsigned long *) *(remothost_p->h_addr_list);

    /*
	non-blocking connect (in case server is not there
	[e.g. power off]), see Stevens 2nd: /lib/connect_nob.c
    */

#ifdef WIN32
    ioctlsocket(l_socket,FIONBIO,&non_blocking);
#else
    ioctl(l_socket,FIONBIO,&non_blocking);
#endif
    status = connect ( l_socket, (LPSOCKADDR)&r_socket_s, sizeof(r_socket_s));
    if ( status == -1)
    {
	 FD_ZERO(&readfds);
	 FD_SET(l_socket,&readfds);
	 writefds = readfds;
	 timeout.tv_sec  = msecs / 1000;
	 timeout.tv_usec = (msecs % 1000) * 1000;
	 status = select(l_socket+1, (void *)&readfds, (void *)&writefds, NULL, (void *)&timeout);
	 if (status > 0 || status < 0)
	 {
	    if (FD_ISSET(l_socket,&readfds) || FD_ISSET(l_socket,&writefds))
	    {
		len = sizeof(error);
		if (getsockopt(l_socket, SOL_SOCKET, SO_ERROR, (char *)&error, &len) < 0)
		   goto error_ret;
	    }
	    else
		goto error_ret;
	    if (error) goto error_ret;
#ifdef WIN32
	    status = ioctlsocket(l_socket,FIONBIO,&blocking);
#else
	    ioctl(l_socket,FIONBIO,&blocking);
#endif
	 }
	 else if (status == 0)
	 {
error_ret:
	    printf ("** Error connecting to Server **\n");
            shutdown ( l_socket , 2 );
	    exit(1);
	 }
    }
    Display();
    closesocket( l_socket );
    exit(1);
    return 0;
}


 

你可能感兴趣的:(tcp,select,CAMAC)