Linuxsocket programming example: echo server program

Source: Internet
Author: User
In this article, we compile the echo server sample program. when the client data is received, the server sends the data to the customer without processing, and uses TCP connection and port 8080 for design.

This article is a sample echo server program. when the client data is received, the server sends the data to the customer without processing, and uses TCP connection and port 8080 for design, the entire process mainly involves socket communication.

First, create a socket. the code is as follows:

Int socketfd;

Socketfd = socket (AF_INET, SOCK_STREAM, 0 );

The socket function is the first function we encounter when writing a socket program. it creates a socket on the specified protocol. its function description is as follows:

# Include

Int socket (int AddressFamily, int Type, int Protocol)

The AddressFamily parameter specifies the network address type to be interpreted in the socket operation. The value is one of the following:

AF_UNIX

Indicates the path of the operating system file.

AF_INET

Internet address

AF_NS

XEROX Network address

The Type parameter table describes the communication semantics, that is, the communication connection method. The parameters are as follows:

SOCK_STREAM

Provides stable and reliable connections and provides two-way communication, such as TCP.

SOCK_DGRAM

Provides connectionless datagram communication, such as UDP.

SOCK_RAW

Only root users can use the internal network protocol and network interface.

Returned value: if the request succeeds, the socket descriptor is returned. if the request fails,-1 is returned. you can use the errno code to check the cause of the error.

Again, bind the socket to the local machine. the code is as follows:

  1. Struct sockaddr_in sa; bzero (& sa, sizeof (sa); sa. sin_family = AF_INET; sa. sin_port = htons (EHCO_PORT); sa. sin_addr.s_addr = htons (INADDR_ANY); bzero (& (sa. sin_zero), 8); if (bind (socketfd, (struct sockaddr *) & sa, sizeof (sa ))! = 0) {printf ("bind failed"); printf ("errno = % d", errno); exit (1 );} else {printf ("bind successfully ");}

In the code above, define a scokaddr_in struct variable sa and fill in the port number and address to be activated by the machine service.

Sa. sin_family = AF_INET;

> Indicates the address type.

Sa. sin_port = htons (EHCO_PORT );

> The port number is 8080.

Sa. sin_addr.s_addr = htons (INADDR_ANY );

> Indicates binding to the local machine

Then, use the bind function to bind the socket you just created as a parameter.

After the binding is complete, the server needs to listen to the connection of the client. Therefore, the listener setting process must be completed by the listen function. the code is as follows:

  1. If (listen (socketfd, MAX_CLIENT_NUM )! = 0)... {printf ("listen error"); exit (1);} else... {printf ("listen successfully ");}

Listen (socketfd, MAX_CLIENT_NUM) indicates listening on socketfd. The maximum number of customers is MAX_CLIENT_NUM.

After listening, you can connect the client to the server. to obtain the client's request, the service must use the accept function, you need to use a sockaddr_in struct to obtain the customer's information. the code is as follows:

  1. Int clientfd; struct sockaddr_in clientAdd; char buff [101]; socklen_t len = sizeof (clientAdd); int closing = 0; while (closing = 0 & (clientfd = accept (socketfd,
  2. (Struct sockaddr *) & clientAdd, & len)> 0) {int n; while (n = recv (clientfd, buff, 100,0)> 0) {printf ("number of receive bytes = % d", n); write (STDOUT_FILENO, buff, n); send (clientfd, buff, n, 0 ); buff [n] = ''; if (strcmp (buff," quit ") = 0) {break;} else if (strcmp (buff," close ") = 0) {// server closingclosing = 1; printf ("server is closing"); break ;}close (clientfd );}

Here, clientfd is the customer's socket. on the server side, each time a customer connection is received, a customer's socket descriptor is returned, and the server communicates with the customer according to it. ClientAdd is the structure of the customer address information. it is filled in the accept function to obtain the customer address information.

  1. While (closing = 0 & (clientfd = accept (socketfd, (struct sockaddr *) & clientAdd, & len)> 0)

Wait for the first customer. when the first customer's request comes to the server, this function will return, and clientfd is the customer's socket descriptor.

Then conduct communication

While (n = recv (clientfd, buff, 100,0)> 0)

Wait for the customer's data. after receiving the data, enter the received data information in the standard and send it back to the customer: send (clientfd, buff, n, 0 );

Here, we use simple commands to control communication. quit indicates that the customer wants to end the communication process, while close indicates that the customer requests to close the server. to close the server, you only need to use the close function.

The complete code is as follows:

  1. # Include # define EHCO_PORT 8080 # define MAX_CLIENT_NUM 10int main () {int socketfd; socketfd = socket (AF_INET, SOCK_STREAM, 0 ); if (socketfd =-1) {printf ("errno = % d", errno); exit (1) ;}else {printf ("socket create successfully ");} struct sockaddr_in sa; bzero (& sa, sizeof (sa); sa. sin_family = AF_INET; sa. sin_port = htons (EHCO_PORT); sa. sin_addr.s_addr = htons (INADDR_ANY); bzer O (& (sa. sin_zero), 8); if (bind (socketfd, (struct sockaddr *) & sa, sizeof (sa ))! = 0) {printf ("bind failed"); printf ("errno = % d", errno); exit (1 );} else {printf ("bind successfully");} // listenif (listen (socketfd, MAX_CLIENT_NUM )! = 0) {printf ("listen error"); exit (1) ;}else {printf ("listen successfully") ;}int clientfd; struct sockaddr_in clientAdd; char buff [101]; socklen_t len = sizeof (clientAdd); int closing = 0; while (closing = 0 & (clientfd = accept (socketfd, (struct sockaddr *) & clientAdd, & len)> 0) {int n; while (n = recv (clientfd, buff, 100,0)> 0) {printf ("number of receive bytes = % d", n); write (STDOUT_FILENO, buff, n); send (clientfd, buff, n, 0 ); buff [n] = ''; if (strcmp (buff," quit ") = 0) {break;} else if (strcmp (buff," close ") = 0) {// server closingclosing = 1; printf ("server is closing"); break ;}close (clientfd);} close (socketfd); return 0 ;}

After cc compilation, you can run the program. here, the program we write is a server program. to complete communication, you have to write a client program, right ???

Well, let's put down the client program first, and test our server program first. here, we use telnet to act as the client for testing. telnet is a good client program, haha:

The local IP address is 192.168.0.69. The entire communication process is as follows:

  1. Linyongting @ linyongting :~ $ Telnet 192.168.0.69 8080 Trying 192.168.0.69... Connected to 192.168.0.69.Escape character is '^]'. hello! This is my first packet. Can you reply to me? Hello! This is my first packet. Can you reply to me? Ohh, U did it! Ohh, U did it! See U next time !!! See U next time !!! QuitquitConnection closed by foreign host. linyongting @ linyongting :~ $ Telnet 192.168.0.69 8080 Trying 192.168.0.69... Connected to 192.168.0.69.Escape character is '^]'. closecloseConnection closed by foreign host.

The connection is made twice. at the first time, it communicates with the server three times. after each message is sent, the same information is received. When you enter quit, the server closes the socket that is idle for communication with the customer, and the communication ends. For the second time, the customer only enters close. after The server responds, the server is immediately closed and the client is also closed. The following is the server display content:

  1. Linyongting @ linyongting :~ /Program/c $./echoServersocket create successfullybind successfullylisten successfully // The first communication number of receive bytes = 53 hello! This is my first packet. Can you reply to me? Number of receive bytes = 16Ohh, U did it! Number of receive bytes = 20see U next time !!! Number of receive bytes = 6 quit // The second communication number of receive bytes = 7 closeserver is closing

When the client inputs quit, it only closes the client, and the server then serves other clients. When the client enters close, the service is closed.

Current problem:

Our server program can only communicate with one client. it can only communicate with the next client after the client issues the quit command.

Related Article

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.