How to use or set up winstock and to send a txt file

This is a discussion on How to use or set up winstock and to send a txt file within the Networking/Device Communication forums, part of the General Programming Boards category; Hi, I been trying to lean how to use winstock but still have little understanding or have done any successful ...

  1. #1
    adr
    adr is offline
    Registered User
    Join Date
    Dec 2005
    Posts
    155

    How to use or set up winstock and to send a txt file

    Hi, I been trying to lean how to use winstock but still have little understanding or have done any successful working connections to host and client (meaning when I try it just doesnt work). Woundering if someone could make a very simple example for me to play with so I could understand it a little more or how to send a .txt file to the client computer like a msg.

    Any help would be nice, even a website that could help little more then the ones posted above on the forum.
    Last edited by adr; 04-27-2007 at 02:29 PM.

  2. #2
    CSharpener vart's Avatar
    Join Date
    Oct 2006
    Location
    Rishon LeZion, Israel
    Posts
    6,471
    you should ask msdn... I believe he is the guy you are looking for...
    The first 90% of a project takes 90% of the time,
    the last 10% takes the other 90% of the time.

  3. #3
    adr
    adr is offline
    Registered User
    Join Date
    Dec 2005
    Posts
    155
    Quote Originally Posted by vart View Post
    you should ask msdn... I believe he is the guy you are looking for...
    LOL, nice ^.^; Yea I still dont get msdn when it comes to alot of things, was hoping for a more detail site for like dumbes ^^: lol. Kinda like this site and how they explain a little more into whats going on and why.

    I do understand that if you have one side of the code that it shouldnt be to hard to make the other side seeing as you are using sending and listening via winsock connections right?

    I've also been finding some code to help out but, I cant seem to find wsock32.lib to link with my project, wasnt sure if Dev-C++ carry the lib or not; also having the same problem for winsock.h and winsock2.h.

  4. #4
    Registered User
    Join Date
    Dec 2004
    Posts
    465
    http://www.gamedev.net/reference/lis...egoryid=30#298
    It's pretty easy to do just look through the tutorials.
    My computer is awesome.

  5. #5
    Malum in se abachler's Avatar
    Join Date
    Apr 2007
    Posts
    3,189
    well, it depends on what exactly you mean by tranfer a text file. If you mean download a text file to your application, the look into the InternetOpen, HttpOpenRequest, etc functions.
    Until you can build a working general purpose reprogrammable computer out of basic components from radio shack, you are not fit to call yourself a programmer in my presence. This is cwhizard, signing off.

  6. #6
    Registered User
    Join Date
    Mar 2005
    Location
    Mountaintop, Pa
    Posts
    1,059
    Woundering if someone could make a very simple example for me to play with so I could understand it a little more or how to send a .txt file to the client computer like a msg.
    It's your responsibility to make sure it's defect free.

    Code:
    #pragma comment( lib, "ws2_32.lib" )
    #include <winsock2.h>
    #include <stdio.h>
    #include <sys/stat.h>
    
    WSADATA wsaData;
    SOCKET mySocket;
    sockaddr_in con;
    SOCKET AcceptSocket;
    
    #define PORT   4370
    
    int GetFileSize(char file[], int *len)
    {
        struct stat status;
        int res;
        res = stat (file, &status);
        if (res != 0)
        {
            fprintf(stderr,"stat function not available\n");
            return (-1);
        }
        *len = (int) status.st_size;
        return (0);
    }
    
    void ServerConnection(char *ip,int port)
    {
        con.sin_family = AF_INET;
        con.sin_addr.s_addr = inet_addr( ip );
        con.sin_port = htons( port );
    
        if ( connect( mySocket, (SOCKADDR*) &con, sizeof(con) ) == SOCKET_ERROR) {
            printf( "Failed to connect.\n" );
            WSACleanup();
            return;
        }
    }
    
    int InitializeServer(int port)
    {
        con.sin_family = AF_INET;
        con.sin_addr.s_addr = inet_addr( "0.0.0.0" );
        con.sin_port = htons( port );
    
        if ( bind( mySocket, (SOCKADDR*) &con, sizeof(con) ) == SOCKET_ERROR) {
            printf( "Failed to connect.\n" );
            WSACleanup();
            return -1;
        }
        if ( listen( mySocket, 1 ) == SOCKET_ERROR )
            printf( "Error listening on socket.\n");
        return 0;
    }
    
    void ListenForClient(void)
    {
        AcceptSocket = SOCKET_ERROR;
        while ( AcceptSocket == SOCKET_ERROR ) {
            AcceptSocket = accept( mySocket, NULL, NULL );
        }
        mySocket = AcceptSocket;
    }
    
    int SendData(char *sendbuffer)
    {
        return send( mySocket, sendbuffer, strlen(sendbuffer), 0 );
    }
    
    
    int ReceiveData(char *receivebuffer,int size)
    {
        int ret = recv( mySocket, receivebuffer, size, 0 );
        receivebuffer[ret] = '\0';
        return ret;
    }
    
    void CloseConnection(void)
    {
        closesocket(mySocket);
    }
    
    
    void ReceiveFile(char *filename)
    {
        int recs, size;
        char record[50] = {0};
        recv( mySocket, filename, 32, 0 );
        send( mySocket, "GOOD", strlen("GOOD"), 0 );
        FILE *filereceive = fopen(filename, "wb");
        recs = recv( mySocket, record, 32, 0 );
        send( mySocket, "GOOD", strlen("GOOD"), 0 );
        record[recs]='\0';
        size = atoi(record);
        while(size > 0)
        {
            char buffer[1030];
    
            if(size>=1024)
            {
                recv( mySocket, buffer, 1024, 0 );
                send( mySocket, "GOOD", strlen("GOOD"), 0 );
                fwrite(buffer, 1024, 1, filereceive);
            }
            else
            {
                recv( mySocket, buffer, size, 0 );
                send( mySocket, "GOOD", strlen("GOOD"), 0 );
                buffer[size]='\0';
                fwrite(buffer, size, 1, filereceive);
            }
            size -= 1024;
        }
        fclose(filereceive);
    }
    
    void TransmitFile(char *filepath)
    {
        char filename[50] = {0};
        char filesize[10] = {0};
        char rec[32] = {0};
        char buffer[1030] = {0};
        int size, i, j;
    
        i =strlen(filepath);
        for(;i>0;i--)if(filepath[i-1]=='\\')break;
        for(j=0;i<=(int)strlen(filepath);i++)filename[j++]=filepath[i];
        if(GetFileSize(filepath, &size ) == -1)
            return;
        itoa(size,filesize,10);
        send( mySocket, filename, strlen(filename), 0 );
        recv( mySocket, rec, 32, 0 );
        send( mySocket, filesize, strlen(filesize), 0 );
        recv( mySocket, rec, 32, 0 );
        FILE *fr = fopen(filepath, "rb");
        while(size > 0)
        {
            if(size>=1024)
            {
                fread(buffer, 1024, 1, fr);
                send( mySocket, buffer, 1024, 0 );
                recv( mySocket, rec, 32, 0 );
            }
            else
            {
                fread(buffer, size, 1, fr);
                buffer[size]='\0';
                send( mySocket, buffer, size, 0 );
                recv( mySocket, rec, 32, 0 );
            }
            size -= 1024;
        }
        fclose(fr);
    }
    
    
    void Server(void)
    {
        char fname[32] = {0};
        char rec[50] = {0};
        if(InitializeServer(PORT) == -1)
        {
            printf("Server initialization failed\n");
            return;
        }
        while (TRUE) {
            ListenForClient();
            while(TRUE)
            {
                ReceiveData(rec,32);
                SendData("GOOD");
                if(strcmp(rec,"TransmitFile")==0)
                {
                    ReceiveFile(fname);
                }
                if(strcmp(rec,"TerminateConnection")==0)break;
            }
            CloseConnection();
        }
    }
    
    void Client(char *ip, char *filepath)
    {
        char rec[32] = {0};
        ServerConnection(ip,PORT);
        SendData("TransmitFile");
        ReceiveData(rec,32);
        TransmitFile(filepath);
        SendData("TerminateConnection");
        ReceiveData(rec,32);
    }
    
    int  main(int argc, char *argv[])
    {
        int iResult = WSAStartup( MAKEWORD(2,2), &wsaData );
        if ( iResult != NO_ERROR )
            printf("WSAStartup() error\n");
        mySocket = socket( AF_INET, SOCK_STREAM, IPPROTO_TCP );
    
        if ( mySocket == INVALID_SOCKET ) {
            printf( "socket() error: %ld\n", WSAGetLastError() );
            WSACleanup();
            return -1;
        }
        if(argc == 1)
            Server();
        else Client(argv[1],argv[2]);
        return 0;
    }

  7. #7
    int x = *((int *) NULL); Cactus_Hugger's Avatar
    Join Date
    Jul 2003
    Location
    Banks of the River Styx
    Posts
    902
    It seems far from defect free.

    Here's what I see, looking at it:
    1) Close your sockets. You fail to do this on the server side with the listening socket (you trash the handle when you accept() your client)
    2) Your protocol doesn't work. If I'm reading the code correctly, there is no way for the client to correctly determine how long the filename is. You send neither a size or a terminating character, such as null. Same issues on the client end. The buffer you store the filename in is 32 bytes wide, yet you ask recv() to blindly recv 32 bytes. If it actually does, then there'll be no null terminator, and you'll be in for segfaults later on.
    3) recv() and send() 's return errors are not checked. This is a recipe for disaster - you might get away with it on a small network / localhost connection, but over a traffic jammed Internet connection, good luck. Also, data doesn't always get sent in packets exactly as you call send() - the data passed from one or more send() calls might get condensed into one packet, broken into many, etc. TCP/IP is a stream protocol, and it is your responsibility for knowing how long your data is.
    4) There is no reason to spam "GOOD" that I can think of. TCP will acknowledge data transfer on it's own, and has the added benefit of being reliable. Just send the data.

    To send an entire buffer:
    Code:
    int FullSend(SOCKET sock, void *buffer, size_t size)
    {
    	size_t sent = 0;
    	int ret;
    	char *cbuffer = (char *) buffer;
    
    	while(sent < size)
    	{
    		ret = send(sock, cbuffer + sent, size - sent, 0);
    		if(ret <= 0)
    		{
    			// network error
    			return ret;
    		}
    		sent += ret;
    	}
    
    	return size;
    }
    Then you can use a sending loop of something like:
    Code:
    	while(bytes_sent < file_size)
    	{
    		// to_send = how many bytes we have left, or 1024
    		// whichever is smallest
    		to_send = file_size - bytes_sent;
    		if(to_send > 1024) to_send = 1024;
    
    		// Read the data.
    		if(fread(buffer, to_send, 1, fp) != 1))
    		{
    			// Error reading
    			fprintf(stderr, "Failed to read from file.\n");
    			fclose(fp);
    			return 1;
    		}
    		ret = FullSend(sock, buffer, to_send);
    
    		if(ret <= 0)
    		{
    			// Socket closed / error
    			fprintf(stderr, "Network error.\n");
    			fclose(fp);
    			return 1;
    		}
    		bytes_sent += ret;
    	}
    You'll need to do similar things on the recv'ing end.

    To the OP: Dev-C++ should have both winsock.h and winsock2.h - you should be including them - if it doesn't work, post your errors. wsock32.lib Dev-C++ doesn't have - it's called "libwsock32.a" in the MinGW world. (libraries are "lib" + name + ".a") Find your linker options for your project and add "-lwsock32" or "-lws2_32" (w/o the quotes) to them.
    Also, to get yourself starting in socket programming, there is a tutorial called "Beej's Guide to Network Programming" and is a good starting place. The only thing I don't think it mentions is the gotcha about send()/recv() - you must check the return value (it might not send/recv everything you ask it to, but it will tell you what it does send/recv - you must account for this, and other errors it might spew. see the man pages for send and recv)
    long time; /* know C? */
    Unprecedented performance: Nothing ever ran this slow before.
    Any sufficiently advanced bug is indistinguishable from a feature.
    Real Programmers confuse Halloween and Christmas, because dec 25 == oct 31.
    The best way to accelerate an IBM is at 9.8 m/s/s.
    recursion (re - cur' - zhun) n. 1. (see recursion)

  8. #8
    adr
    adr is offline
    Registered User
    Join Date
    Dec 2005
    Posts
    155
    Wow, that helps out alot. I think I am understand it somewhat now. Thanks for all the help guys ^^ I'll see what I can do from all this and if I have any problems i'll ask.

  9. #9
    Woof, woof! zacs7's Avatar
    Join Date
    Mar 2007
    Location
    Australia
    Posts
    3,459
    And its winsock (Windows Sockets, Based off BSD sockets), not winstock

Popular pages Recent additions subscribe to a feed

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21