简体   繁体   中英

Socket Programming - Server content written to Client (write())

I am writing a file navigator, that connects a client to a server and lets the user list all the files in the current directory of the server (the server location).

Suppose the directory contains the following files:

test.txt
Makefile
server.c

Now, I want the user (on client side) to be able to get a list of all the files/foldes on the server end.

I have already written a WORKING piece of code that displays all files, but only on the SERVER side. It looks as follows:

void print_content(int socket_num) {
    struct dirent *entry;   //Entry
    DIR *dir_stream;    //Directory stream
    dir_stream = opendir("./"); //Open current directory
    if(dir_stream != NULL) {
        while((entry = readdir(dir_stream))) {
            printf("%s\n", entry->d_name); //Gets name
            write(socket_num, entry->d_name, 1024); //WRITE?
        }
        (void) closedir(dir_stream);
    }
    else {
        error("Problems with directory");
    }
}

As mentioned, this prints out correctly on the SERVER side.

However, is there a way to easily send these strings to the CLIENT, instead of using the write() function?

In other words, is there a function more similar to printf() than write(), that writes to a client?

In other words, is there a function more similar to printf() than write(), that writes to a client?

Yes, there's fprintf() , which you can use for the purpose if you first fdopen() a stream ( ie a FILE * ) around your connected socket's file descriptor. You would be well advised to fflush() after all the fprintf() s to be sure the last bits are sent without delay, and definitely before discarding the stream.

HOWEVER, you probably don't want to do that. [ f ] printf() is for formatting data; sending it to a chosen destination is a secondary, albeit important, consideration. Unless the client you describe is exceedingly thin, you probably want the client, not the server, to perform formatting. In that case, what you need to do is serialize [the needed parts of] a struct dirent , and send those to the client, for it to use as it pleases. If you just pass formatted data over the socket, then there's not much the client can do other than slurp up all the incoming data and spit it out as-is in the UI. Only and forever. That's more or less what I mean by "exceedingly thin".

Additionally, if you do create a stream, be aware that when you close it, you will close the underlying socket, too. If you discard it without closing it, on the other hand, then that will constitute a resource leak.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM