Link to home
Start Free TrialLog in
Avatar of bradleyb1537
bradleyb1537

asked on

Winsock Help!!!

Avatar of bradleyb1537
bradleyb1537

ASKER

Im trying to figure out the problem in my code I beleive from everything ive read that this shoudl work but when i run the program as a server then as a client the server does not display the correct information the code is posted below:

//Link with Wsock32.lib
#include <iostream.h>
#include <stdio.h>
#include <winsock2.h>

SOCKET SockIn,SockOut;
char buff[100];
char debarray[1000];
void DebugIt(char *info)
{
    FILE *fp=fopen("debugs.txt","a+");
      fprintf(fp,"%s",info);
      fclose(fp);
}

void DebugInit()
{
    FILE *fp=fopen("debugs.txt","w");
      fclose(fp);
}


int StartServer(SOCKET sock, int port)
{    
   WSADATA w;
   SOCKET come;
 

      if(WSAStartup(MAKEWORD(2,2),&w)!=0) {
            cout << "\nWSAStartup Error!";
            return 0;
      }
   come = socket(AF_INET,SOCK_STREAM,0);
   sockaddr_in addr; //the address structure for a TCP socket

   addr.sin_family = AF_INET; //Address family internet
   addr.sin_port = 50; //Receiving port
   addr.sin_addr.s_addr = inet_addr("127.0.0.1"); //htonl(INADDR_ANY);

   if(bind(come,(SOCKADDR *)(&addr),sizeof(addr))==SOCKET_ERROR)
   {
         cout << "Bind failed.\n";
         return 0;
   }

   if(listen(come,3)==SOCKET_ERROR)
   {
         cout << "Listen failed.\n";
         return 0;
   }
   sock = accept(come,NULL,NULL);
   if(sock==SOCKET_ERROR) {
         cout << "Accept Error\n";
         return 0;    
   }
   return 1;
}

int StartClient(SOCKET SockOut, int port, char *ip)
{
WSADATA w;
      if(WSAStartup(MAKEWORD(2,2),&w)!=0) {
            cout << "\nWSAStartup Error!";
            return 0;
      }
   sockaddr_in target;
SockOut=socket(AF_INET,SOCK_STREAM,0);
   target.sin_family = AF_INET;
   target.sin_port = 50; //SERVER listening port
   target.sin_addr.s_addr = inet_addr("127.0.0.1"); //inet_addr(ip);

DebugIt("Can't connect! Aborting!\n");
   if(connect(SockOut,(LPSOCKADDR)&target,sizeof(target)) !=0)
   {
         cout << "Connect failed.\n";
      WSACleanup();
      exit(0);
   }

   strcpy(buff,"This is a TEST!!!");
   send(SockOut,buff,sizeof(buff),0);

   strcpy(buff,"000");
   send(SockOut,buff,sizeof(buff),0);
      return 1;
}

void Client()
{
      while(buff[0] != '0' || buff[1] != '0' || buff[2] != '0')
      {
      cout << "\nInput: ";
      //cin >> buff;
      cin.getline(buff,100,'\n');
      send(SockOut,buff,sizeof(buff),0);
      }
}

void Server()
{
      int RetVal=SOCKET_ERROR;
      cout << "In Server!";
      DebugIt("\nIn Server()");
         //while(buff[0] != '0' || buff[1] != '0' || buff[2] != '0')
          //while(RetVal==SOCKET_ERROR && (buff[0] != '0' || buff[1] != '0' || buff[2] != '0'))
            //{
            RetVal=recv(SockIn,buff,sizeof(buff),0);
                  if((RetVal==0) || (RetVal==WSAECONNRESET) )//|| (RetVal==WSAECONNABORT))
                  {
                        cout << "Connection closed on other end!\n";
                        return;
                  }
            //if(buff[0] == 'c' || buff[1] == 'm' || buff[2] == 'd')
                  //{
                        cout << buff;
                        DebugIt(buff);
                  //}

      //}//End of while 000 was entered

                              cout << buff;
                        DebugIt(buff);
      DebugIt("\nDone Server()");
      cout << "\nDone Server()";

}

int main()
{
      int i;
      DebugInit();
      cout << "\n1: Server\n2: Client\n";
      cin >> i;
      if(i==1)
            if(StartServer(SockIn,9110)) {
                  cout << "\nStarted fine";
                  Server();
            }
            else
                  cout << "\nERROR!!\n";
      if(i==2)
            if(StartClient(SockOut,9110,"127.0.0.1")) {
                  cout << "\nClient Working";
                  //Client();
            }
            else
                  cout << "\nERROR!!\n";
      closesocket(SockIn); closesocket(SockOut);
      WSACleanup();
      //exit(0);
      return 0;

}
 
StartServer() needs to pass its SOCKET by reference:

  int StartServer(SOCKET &sock, int port)
   
After you finish sending your data in StartClient(), call shutdown():

  strcpy(buff,"This is a TEST!!!");
  send(SockOut,buff,sizeof(buff),0);

  strcpy(buff,"000");
  send(SockOut,buff,sizeof(buff),0);

  shutdown(SockOut, 1);
  return 1;

Your Server() function was a mess.  Here it is simplified:

  void Server()
  {
     int RetVal;
     cout << "In Server!";
     DebugIt("\nIn Server()\n");

     while ((RetVal=recv(SockIn,buff,sizeof(buff),0)) != 0)
     {
        if (RetVal==SOCKET_ERROR)
        {
           cout << "Connection closed with " << WSAGetLastError() << "\n";
           return;
        }

        cout << buff;
        DebugIt(buff);
     }

     DebugIt("\nDone Server()");
     cout << "\nDone Server()";
  }

Enjoy!
Yep, just bet me to it TascoDLX !

Also bradleyb1537,

I find it is always useful to split up into separate client and server files; this makes it much more clear when it comes to debugging and also when it comes to other people maintaining your code.
I rewrote my code with your suggestion of passing by reference and I still get an invalid socket return from my recv and it fails to the message. My new code is as follows:
//link with wsock32.lib

#include <iostream.h>
#include <stdio.h>
#include <winsock.h>

#define PORT 50

SOCKET sock;
char buff[1024];

void Server();
void Client();

int StartServer(SOCKET &sock, short port)
{
     gethostname(buff,sizeof(buff));
     cout << "\nServer on computer: " << buff << " Port:" << port;

     sock=socket(AF_INET,SOCK_STREAM,IPPROTO_TCP);
     if(sock==INVALID_SOCKET)
     {
          cout << "\nInvalid Socket";
          return 0;
     }

     SOCKADDR_IN addr;
     addr.sin_family=AF_INET;
     addr.sin_addr.s_addr=INADDR_ANY;
     addr.sin_port=htons(port);

     cout << "\nBinding.";
     if(bind(sock,(LPSOCKADDR)&addr,sizeof(addr))==SOCKET_ERROR)
     {
          cout << "\nBind error!";
          return 0;
     }
     cout << "\nListening.";
     if(listen(sock,SOMAXCONN)==SOCKET_ERROR)
     {
          cout << "\nError Listening.";
          return 0;
     }

     SOCKET remoteSock;

     remoteSock=accept(sock,NULL,NULL);
     if(remoteSock==INVALID_SOCKET)
     {
          cout << "\nError Accepting.";
          return 0;
     }

   return 1;
}

int StartClient(SOCKET &sock, short port, char *ip, char *hostname)
{
     sock=socket(AF_INET,SOCK_STREAM,IPPROTO_TCP);
     if(sock==INVALID_SOCKET)
     {
          cout << "\nInvalid Socket";
          return 0;
     }

     SOCKADDR_IN addr;
     addr.sin_family=AF_INET;
     addr.sin_port=htons(port);
     if(hostname==NULL)
          addr.sin_addr.s_addr=inet_addr(ip);
     else
     {
          LPHOSTENT lpHostEntry;
          lpHostEntry=gethostbyname(hostname);
          if(lpHostEntry==NULL)
          {
          cout << "\nInvalid Hostname";
          return 0;
          }
          addr.sin_addr=*((LPIN_ADDR)*lpHostEntry->h_addr_list);
     }

     cout << "\nConnect().";
     if(connect(sock,(LPSOCKADDR)&addr,sizeof(addr))==SOCKET_ERROR) {
          cout << "\nConnect Error.";
          return 0;
     }

     return 1;
}


int main()
{
     WORD VersionRequest=MAKEWORD(1,1);
     WSADATA WSAData;
     int i;


     WSAStartup(VersionRequest, &WSAData);
     gethostname(buff,sizeof(buff));
     cout << "\nComputer name: " << buff;

     cout << "\n\nChoose your connection:\n1: Server\n2: Client(connect with ip)\n3: Client(connect with hostname)\n";
     cin >> i;
     if(i==1)
          if(StartServer(sock,PORT)) {
               cout << "\nStarted fine";
               Server();
          }

     if(i==2) {
               cout << "\nIP Adress:";
               cin >> buff;
               StartClient(sock,PORT,buff,NULL);
               Client();
          }

     if(i==3)
          {
               cout << "\nHost name:";
               cin >> buff;
               StartClient(sock,PORT,NULL,buff);
               Client();
          }
     closesocket(sock);
     WSACleanup();
     return 0;

}

void Client()
{
     int RetVal;
     sprintf(buff,"Hello from client!");
     RetVal=send(sock,buff,sizeof(buff)-1,0);
     if(RetVal==INVALID_SOCKET)
     {
          cout << "\nError Sending.";
     }
     shutdown(sock,1);
}

void Server()
{
     int RetVal;
     cout << "\nIn Server!";

     RetVal=recv(sock,buff,sizeof(buff)-1,0);
     if(RetVal==INVALID_SOCKET)     cout << "\nError Receiving.";

     cout << "\nRecieved: " << buff;
     cout << "\nDone Server()";

}
ASKER CERTIFIED SOLUTION
Avatar of TascoDLX
TascoDLX

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Great !! thanx for all the help hope these points are enough