Socket programming instance
/ * Client.c * / #include #include #include #include #include int main () {int sockfd; int len; struct sockaddr_un address; int result; char ch = A; sockfd = socket (AF_UNIX, SOCK_STREAM, 0) ; / * Established the client's socket, use AF_UNIX UNIX domain protocol * / address.sun_family = Af_Unix; strcpy (address.sun_path, "server_socket"); len = sizeof (address); / * Create server socket Address, including a socket type, name * / result = connect (SockFD, Struct SockAddr *) & address, len); if (Result == - 1) {PERROR ("OOPS: Client1"); exit (1); } / * The above tried to establish a connection with the server socket. Once the connection is successful, then continue the following program * / write (sockfd, & ch, 1); read (SockFD, & ch, 1); / * If successful, Send a character to the server side, then read the server's answer * / printf ("Char from Server =% C / N", CH); Close (SOCKFD); exit (0);} / * server.c * / # include #include #include #include #include int main () {int server_sockfd, client_sockfd; int server_len, client_len; struct sockaddr_un server_address; struct sockaddr_un client_address; unlink ( "server_socket"); / * If the same name exists in the socket, the first Delete * / server_sockfd = socket (AF_UNIX, SOCK_STREAM, 0); / * Built the set of interfaces, then there is no name * / server_address.sun_family = AF_UNIX; STRCPY (Server_Address.sun_path , "server_socket"); server_len = sizeof (server_address); bind (server_sockfd, (struct socddr *) & server_address, server_len; listen (server_sockfd, 5); / * Create a listener queue. Wait for user connection request * / while 1) // Enter the listening status of unlimited cycles {char ch; Printf ("Server Waiting / N"); client_sockfd = accept (server_sockfd, (strunt socketdr *) & client_address, & client_len); / * Accept a customer request * / Read (Client_Sockfd, & Ch, 1); / * Because the connection is established, the customer will first send a message, so the server reads * / ch ; Write (client_sockfd, & ch, 1); / * Do the read string Simple processing, return * / close (client_sockfd);}}