Winsock programming

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • Har
    New Member
    • Jun 2007
    • 3

    Winsock programming

    I have created a small client application with loopback address (127.0.0.1) so that same machine act as server and client. but i want to know whether we have to create seperate server application and run that seperately inorder to connect with the same machine.
    Even if i run client and server application seperately client application shows the error ie., "Not able to connect program aborted".
    In the server application it just run without displaying anything on the screen.
    if u have any source code in C++ which is working fine u just send it to me..Im new to the socket programming So pls can anyone help me out..

    Thanks,
    Haroon.
  • Banfa
    Recognized Expert Expert
    • Feb 2006
    • 9067

    #2
    The loop back should work. I write WinSock based server applications and I test them by writing simulator programs for the remote pieces of equipment and I run them both on the same machine and the connect without problem.

    Comment

    • Har
      New Member
      • Jun 2007
      • 3

      #3
      Originally posted by Banfa
      The loop back should work. I write WinSock based server applications and I test them by writing simulator programs for the remote pieces of equipment and I run them both on the same machine and the connect without problem.
      Actually i have written the winsock server/client application which i will include it below.In that i have got the server waiting for too long i dont know why..and the client is not able to connect the socket..whether i have to run both the application to establish the connection throu socket?in client application im getting the error "Connect Error. Program aborted"..im using visual C++ compiler.

      Client :

      #include <winsock.h>
      #include <iostream.h>
      int gPort = 1150;
      void main()
      {
      SOCKET lhSocket;
      SOCKADDR_IN lSockAddr;
      WSADATA wsaData;
      int lConnect;
      int lLength;
      char lData[]="SendData";
      if(WSAStartup(M AKEWORD(2,0),&w saData) != 0)
      {
      cout<<"Socket Initialization Error. Program aborted\n";
      return;
      }
      lhSocket = socket(AF_INET, SOCK_STREAM,IPP ROTO_TCP);
      if(lhSocket == INVALID_SOCKET)
      {
      cout<<"Invalid Socket "<<GetLastError ()<<". Program Aborted\n"<<end l;
      }
      memset(&lSockAd dr,0, sizeof(lSockAdd r));
      lSockAddr.sin_f amily = AF_INET;
      lSockAddr.sin_p ort = htons(gPort);
      lSockAddr.sin_a ddr.s_addr = inet_addr("127. 0.0.1");
      lConnect = connect(lhSocke t,(SOCKADDR *)&lSockAddr,si zeof(SOCKADDR_I N));
      if(lConnect != 0)
      {
      cout<<"Connect Error. Program aborted\n";
      return;
      }
      lLength = send(lhSocket,l Data,strlen(lDa ta),0);
      if(lLength < strlen(lData))
      {
      cout<<"Send Error.\n";
      }
      closesocket(lhS ocket);
      return;
      }


      Server:

      #include <winsock2.h>
      #include <iostream.h>

      #define PORT 1250
      #define BUFFERSIZE 8192

      typedef struct _MYSOCKET_INFOR MATION {
      CHAR Buffer[BUFFERSIZE];
      WSABUF DataBuf;
      SOCKET Socket;
      DWORD SendBytes;
      DWORD RecvBytes;
      } SOCKET_INFORMAT ION, * LPSOCKET_INFORM ATION;

      BOOL CreateSocketInf ormation(SOCKET s);
      void FreeSocketInfor mation(DWORD Index);

      DWORD TotalSockets = 0;
      LPSOCKET_INFORM ATION SocketList[FD_SETSIZE];

      void main(void)
      {

      //some of the basic declarations required for this winsock tutorial
      SOCKET ListenSocket;
      SOCKET AcceptSocket;
      SOCKADDR_IN InternetAddr;
      WSADATA wsaData;
      FD_SET Writer;
      FD_SET Reader;
      ULONG NonBlock;
      DWORD Flags;
      DWORD Total;
      DWORD Ret;
      DWORD i;
      DWORD SendBytes;
      DWORD RecvBytes;


      if ((Ret = WSAStartup(MAKE WORD(2,0),&wsaD ata)) != 0)
      {
      cout<<"Start up failed";
      }

      // Create a socket for the winsock tutorial.

      if ((ListenSocket = WSASocket(AF_IN ET, SOCK_STREAM, 0, NULL, 0,
      WSA_FLAG_OVERLA PPED)) == INVALID_SOCKET)
      {
      cout<<"Winsock tutorial error: WSASocket() failed \n"<< WSAGetLastError ();
      return;
      }

      InternetAddr.si n_family = AF_INET;
      InternetAddr.si n_addr.s_addr = htonl(INADDR_AN Y);
      InternetAddr.si n_port = htons(PORT);

      if (bind(ListenSoc ket, (SOCKADDR *) &InternetAdd r, sizeof(Internet Addr))
      == SOCKET_ERROR)
      {
      cout<<"Winsock tutorial error: Binding failed \n"<<WSAGetLast Error();
      return;
      }

      if (listen(ListenS ocket, 5))
      {
      cout<<"Winsock tutorial error: listen failed \n"<< WSAGetLastError ();
      return;
      }

      // Change the socket mode on the listening socket from blocking to non-block

      NonBlock = 1;
      if (ioctlsocket(Li stenSocket, FIONBIO, &NonBlock) == SOCKET_ERROR)
      {
      cout<<"ioctlsoc ket() failed \n";
      return;
      }

      while(TRUE)
      {
      // Initialize the Read and Write socket set.
      FD_ZERO(&Reader );
      FD_ZERO(&Writer );

      // Check for connection attempts.
      FD_SET(ListenSo cket, &Reader);

      // Set Read and Write notification for each socket based on the
      // current state the buffer.

      for (i = 0; i < TotalSockets; i++)
      if (SocketList[i]->RecvBytes > SocketList[i]->SendBytes)
      FD_SET(SocketLi st[i]->Socket, &Writer);
      else
      FD_SET(SocketLi st[i]->Socket, &Reader);

      if ((Total = select(0, &Reader, &Writer, NULL, NULL)) == SOCKET_ERROR)
      {
      cout<<"Winsock tutorial error: select function returned with error \n"<< WSAGetLastError ();
      return;
      }

      // Check for arriving connections on the listening socket.
      if (FD_ISSET(Liste nSocket, &Reader))
      {
      Total--;
      if ((AcceptSocket = accept(ListenSo cket, NULL, NULL)) != INVALID_SOCKET)
      {

      // Set the accepted socket to non-blocking mode so the server will
      // not get caught in a blocked condition on WSASends

      NonBlock = 1;
      if (ioctlsocket(Ac ceptSocket, FIONBIO, &NonBlock) == SOCKET_ERROR)
      {
      cout<<"Winsock tutorial error: ioctlsocket() failed with error \n", WSAGetLastError ();
      return;
      }

      if (CreateSocketIn formation(Accep tSocket) == FALSE)
      return;
      }
      else
      {
      if (WSAGetLastErro r() != WSAEWOULDBLOCK)
      {
      cout<<"accept() failed with error %d\n", WSAGetLastError ();
      return;
      }
      }
      }

      // Check each socket for Read and Write notification for Total number of sockets

      for ( i = 0; Total > 0 && i < TotalSockets; i++)
      {
      LPSOCKET_INFORM ATION SocketInfo = SocketList[i];

      // If the Reader is marked for this socket then this means data
      // is available to be read on the socket.

      if (FD_ISSET(Socke tInfo->Socket, &Reader))
      {
      Total--;

      SocketInfo->DataBuf.buf = SocketInfo->Buffer;
      SocketInfo->DataBuf.len = BUFFERSIZE;

      Flags = 0;
      if (WSARecv(Socket Info->Socket, &(SocketInfo->DataBuf), 1, &RecvBytes,
      &Flags, NULL, NULL) == SOCKET_ERROR)
      {
      if (WSAGetLastErro r() != WSAEWOULDBLOCK)
      {
      cout<<"Winsock tutorial: Receive failed with error\n";

      FreeSocketInfor mation(i);
      }
      continue;
      }
      else
      {
      SocketInfo->RecvBytes = RecvBytes;
      cout<<SocketInf o->DataBuf.buf<<" \n";

      // If zero bytes are received, this indicates connection is closed.
      if (RecvBytes == 0)
      {
      FreeSocketInfor mation(i);
      continue;
      }
      }
      }


      // If the Writer is marked on this socket then this means the internal
      // data buffers are available for more data.

      if (FD_ISSET(Socke tInfo->Socket, &Writer))
      {
      Total--;

      SocketInfo->DataBuf.buf = SocketInfo->Buffer + SocketInfo->SendBytes;
      SocketInfo->DataBuf.len = SocketInfo->RecvBytes - SocketInfo->SendBytes;

      if (WSASend(Socket Info->Socket, &(SocketInfo->DataBuf), 1, &SendBytes, 0,
      NULL, NULL) == SOCKET_ERROR)
      {
      if (WSAGetLastErro r() != WSAEWOULDBLOCK)
      {
      cout<<"Send failed with error\n";
      FreeSocketInfor mation(i);
      }

      continue;
      }
      else
      {
      SocketInfo->SendBytes += SendBytes;

      if (SocketInfo->SendBytes == SocketInfo->RecvBytes)
      {
      SocketInfo->SendBytes = 0;
      SocketInfo->RecvBytes = 0;
      }
      }
      }
      }
      }
      }

      BOOL CreateSocketInf ormation(SOCKET s)
      {
      LPSOCKET_INFORM ATION SI;

      cout<<"Accepted socket\n";

      if ((SI = (LPSOCKET_INFOR MATION) GlobalAlloc(GPT R,
      sizeof(SOCKET_I NFORMATION))) == NULL)
      {
      cout<<"Winsock tutorial error: GlobalAlloc() failed\n";
      return FALSE;
      }

      // Prepare SocketInfo structure for use.

      SI->Socket = s;
      SI->SendBytes = 0;
      SI->RecvBytes = 0;

      SocketList[TotalSockets] = SI;

      TotalSockets++;

      return(TRUE);
      }

      void FreeSocketInfor mation(DWORD Index)
      {
      LPSOCKET_INFORM ATION SI = SocketList[Index];
      DWORD i;

      closesocket(SI->Socket);

      cout<<"Closing socket\n";

      GlobalFree(SI);

      // Remove from the socket array
      for (i = Index; i < TotalSockets; i++)
      {
      SocketList[i] = SocketList[i + 1];
      }

      TotalSockets--;
      }

      Comment

      • Har
        New Member
        • Jun 2007
        • 3

        #4
        Please anyone help me out

        Could you please help me to solve the problem.Since im new to this type of socket programming i have been in desperate situation. im going to develop a simulator to test the remote devices in the same machine.i think the first step to develop is to connect both the client and server in the same machine through the socket programming but im not able to connect it.both the client and server application runs without any errors but still while running it shows connect error which i have mentioned in my previous post along with the source code.
        is there any configuration needed in the system?
        Since Im beginner to the socket programming please anyone guide me and help me out of the problem.and also guide me in the simulator program for remote devices.

        Comment

        Working...