Upload and download files on the Http server (3) (1)

Source: Internet
Author: User

Upload and download files on the Http server (3) (1)

I. Introduction

The general process has been explained in the first two chapters. When designing an Http server, I designed a four-layer structure. The bottom layer is the network transmission layer, that is, socket programming. The next layer is the Request and Response layer, called Request and Response. The above layer is the URL parsing process direction layer. The top layer is designed as the index layer. This layer mainly indexes files in memory when multiple files are used to speed up file search. Or it may be other content. This time also includes some page content displayed by the browser. These can be added by the reader.

When I write this chapter, I don't know whether to explain it from the top down or from the bottom up to help readers better understand my design. In thinking..., the final choice starts from the underlying socket layer. If you have any questions, refer to the content of the first two chapters.

Ii. socket programming

At the beginning of encapsulation, you can look at the book Unix network programming. The main content is still above, and the main code is roughly the same as that in this book. Here I will sort it out. I will not explain all the APIs. I will not explain the APIs on the client. I just want to explain the APIs used by the server.

At the beginning, I need to talk about two sockets. As long as it is explained for the following content. When we start socket programming, we need to create a socket to connect to the remote end. This sentence contains two sockets. One is the listening socket, and the other is the connection socket. For example, the listening socket is the uncle in our dormitory, and the connection socket is ours. When there was a connection called a courier arriving downstairs, he was found by the uncle in the dormitory building. In fact, he listened to the socket and found a connection. Then the Lord told us that your courier was here, and then we went downstairs and signed the courier to get the courier. This was the connection.

We learned from the above that we need a listening socket, that is, the dormitory uncle. Create as follows:

int socket(int family,int type,int protocal);

No. The returned value is the socket, which is actually an integer or a file descriptor. Because all devices in linux are files, a unique integer can be used to indicate a specific meaning. The returned result is-1. Table creation fails. Generally, the TCP programming parameter is set to listenfd = socket (AF_INET, SOCK_STREAM, 0). A stream socket is created. For details, see the above-mentioned books.

Next we need to bind the socket. Why? Because we applied for a socket from the system (dormitory uncle), but he does not have a work location yet, we need to arrange a work location for him. The work location, that is, the port. to indicate a unique work location, the computer needs both the IP address and port to determine the unique location.

int bind(int sockfd,const struct sockaddr*myaddr,socklen_t addrlen);

If 0 is returned,-1 is returned. The first parameter represents the socket listenfd just created. Struct sockaddr is a general socket structure. In fact, the structure we transmit, such as struct sockaddr_in {}, needs to be forcibly converted because these APIs are old and historical, it is mainly because there is no void * type before. Socklen_t is an unsigned integer. The call method is generally

bind(listenfd,(struct sockaddr*)&serveraddr,sizeof(serveraddr));

The serveraddr is filled as follows:

Bzero (& serveraddr, sizeof (serveraddr ));

Serveraddr. sin_family = AF_INET;

Serveraddr. sin_addr.s_addr = htonl (INADDR_ANY );

Serveraddr. sin_port = htons (PORT );

The serveraddr type is indeed struct sockaddr_in;

Now, I have arranged a work place for the dormitory master. Next I just want the master to work, or I will apply for a job...

int listen(int sockfd,int backlog);

If 0 fails to be returned successfully, the value-1 is returned. The first socket is the listening socket. The backlog parameter mainly involves the problem of unfinished connection queue and completed connection queue. Now we can understand it as the maximum number of connections. For more information, see the book above.

The last one is when the Lord finds the courier and confirms his identity and calls us down. This is the following api

Int accept (int sockfd, struct sockaddr * chliaddr, socklent_t * addrlen );

If the connection is successful, the connection socket is returned. Otherwise,-1 is returned. Among the three parameters, the first is the listening socket listenfd, and the second and third can get the identities of the connection provider. The IP address and port.

Generally, if you do not need to set it to NULL. Example:

Clientlen = sizeof (struct sockaddr_in );

Int fd = accept (listenfd, (struct sockaddr *) & clientaddr, & clientlen );

If you do not enter a default value for clientlen, the program will report an error. Although this parameter is called length, we need to set the size first.

Next we will communicate with the courier. We accept the courier who handed it to me. This behavior is read. Write the content to your bucket.

ssize_t read(int sockfd,void*buf,size_t nbyte);

The number of actually read bytes is returned after successful reading. If 0 is returned, it indicates that the data has been delivered. If 0 is returned, it indicates that the input is incorrect. buf indicates that the data is stored and received by itself. nbyte indicates the size of the space. Remember that sockfd is now filled with the connection socket. It is our own, not the old man.

ssize_t write(int sockfd,const void* buf,size_t nbytes);

This function writes the content of nbytes in the buf into the sockfd socket and sends it to the other party. The number of actually written bytes is returned for success, and-1 is returned for failure.

The required APIs have been completed here, but the last two read and write operations are a bit special, because in some linux systems, when the system is interrupted, the read or write operations may be stopped. We need to call this function again. To obtain data correctly, you need to enter some code. It is not enough to call these two functions.

The following is the code snippet of this socket. Encapsulate the Socket in a Socket class with a namespace of TCP.

Header file (include/socket. h)

1 /*2 * tcp.h3 *4 */56 #ifndef SOCKET_H_7 #define SOCKET_H_8 #include
 9 #include
 10 #include
 11 #include
 12 #include
 13 #include 
 14 //#include 
 15 namespace TCP{16 class Socket {17 public:18 Socket();19 ~Socket();20 int server_socket();21 int server_listen();22 int server_accept();23 int server_bind();24 void server_init();25 void getClient(sockaddr_in* caddr);26 int server_read(int fd,char*recvBuf,ssize_t maxlen);27 int server_write(int fd,char*sendBuf,ssize_t maxlen);28 void server_close(int confd) ;29 private:30 int __readline(int fd,char*recvBuf,ssize_t maxlen) ;31 int __writen(int fd,char*sendBuf,ssize_t maxlen) ;32 int listenfd;33 int confd;34 struct sockaddr_in serveraddr;35 socklen_t serverlen;36 static const int PORT=80;37 };38 }39 #endif /* SOCKET_H_ */


Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.