Talk C Chestnut Bar (156th time: C Language Instance--flow socket communication based on Af_unix domain)

Source: Internet
Author: User

Ladies and gentlemen, crossing, the last time we said the example of getting socket address, this time we say the example is: based on the Af_unix domain of the flow socket communication . Gossip Hugh, words return to the positive. Let's talk C chestnuts together!

Crossing, we are in front Zhanghuizhong introduced the socket communication process and the details of the socket, the total feeling is still missing something, for a moment I really can't remember. It's like we have recipes and ingredients, so we can make a delicious meal. Ah! There it is. When it comes to delicious food, inspiration comes. What we lack is a comprehensive walkthrough of sockets, that is, to string together the knowledge in the previous chapter, and then give an example of using socket knowledge for socket communication. This is an example of a delicious meal, let's make this delicious meal together. Our first dish is: flow socket communication based on the Af_unix domain.

  • recipe for making your first dish: the flow socket process.
  • produce the ingredients for the first dish : the interface of the stream socket, socket properties, socket address information.

Crossing, the above content, we in the previous chapter back in detail, if you forget, you can refer to the previous content, the focus is the 147th back content, because this is our recipe. More unhelpful, we demonstrate by specific code:

The server-side communication process and its code
//1. Creating a server-side socketSERVER_FD = socket (Af_unix,sock_stream,0);//2. Setting properties for server-side sockets: Domain, type, and protocol;    memset(&address,0,sizeof(structSockaddr_un)); address.sun_family = Af_unix;strncpy(Address.sun_path,socket_path,sizeof(Address.sun_path)-1);//3. Bind the server-side socket to the server's addressAddr_len =sizeof(structSockaddr_un); res = bind (SERVER_FD, (structSOCKADDR *) &address,addr_len);//4. Create a socket queue, prepare for communication, and start listening for communication connection requests from clientsres = Listen (SERVER_FD,2);//5. Accept the connection request from the client and obtain a socket that matches the clientCLIENT_FD = Accept (server_fd,null,null);//6. Reading data through socketsres = read (client_fd,buf,buf_size);printf("[Server] receiving data (%s) from client by socket\n", buf);//7. Releasing sockets, turning off communicationres = close (CLIENT_FD); res = close (SERVER_FD);
The client's communication process and its code
//1. Creating a client socket;CLIENT_FD = socket (Af_unix,sock_stream,0);//2. Setting properties for client sockets: domain, type, and protocol;    memset(&address,0,sizeof(structSockaddr_un)); address.sun_family = Af_unix;strncpy(Address.sun_path,socket_path,sizeof(Address.sun_path)-1); Addr_len =sizeof(structSockaddr_un);//3. Connect using the client socket and the server;res = connect (CLIENT_FD, (structSOCKADDR *) &address,addr_len);//4. sending data via sockets;    printf("[Client] sending data (%s) to server by socket \ n", buf); res = write (Client_fd,buf,sizeof(BUF));//5. Releasing sockets, disconnecting client from server-side communication;res = close (CLIENT_FD);

Crossing, the above is the core code, the complete code put in my resources, you can click here to download the use.

We need to compile the server-side code and the client code separately and compile it into different executable files:

$ gcc Ex090_UnixStreamSocketClient.c  client  //编译客户端$ gcc Ex090_UnixStreamSocketServer.c  server  //编译服务器端

Crossing, delicious food is ready, let's try it together, how to taste it? Of course it is running the program, do you want to eat the code? The following is the results of the operation of the program, please refer to:

$ ./Server&//Run the server in the back[1]6968$ ./Client             //Run the clientPlease input8Chars forUsing. Hello [Client] Sending data (hello) toServer  bySocket//Successfully send data[Server] Receiving data (hello) fromClient  bySocket//successfully received data$ ./Client            //Run the client againPlease input8Chars forUsing. socket[Client] Sending data (socket) toServer  bySocket [Server] Receiving data (socket) fromClient  bysocket$./Client            //Last Run clientPlease input8Chars forUsing. good[Client] Sending data (good) toServer  bySocket [Server] Receiving data (good) fromClient  bysocket[1]+ done.Server      //server stopped running

Crossing, as can be seen from the results above, the client sends data to the server through a socket, and the server receives the data from the client through the socket, so that the client and the server can communicate through the socket. In addition, we have three of communications, the number of communications can be controlled, or even written unlimited time is also possible. Each communication can be considered as a complete communication process, the data we send during the communication is a string, and in three communications we send three different strings.

As we said earlier, socket communication based on the Af_unix domain is essentially through a file. Next, let's verify.

The directory of the file is set in the address of the socket: #define SOCKET_PATH "/tmp/socket_test"

$ ll /tmp/srwxr-xr-x  1 tom  tom      0  52810:40 SOCKET_TEST=//省略掉其它无关的信息

You can see that there is a file named Socket_test, and the file type is S, which is the socket type.

You crossing, the example of flow socket communication based on Af_unix Domain Let's just talk about this. I want to know what the following example, and listen to tell.

Talk C Chestnut Bar (156th time: C Language Instance--flow socket communication based on Af_unix domain)

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.