The realization of the chat function of Linux peer

Source: Internet
Author: User
Tags stdin htons

Linux-Peer chat feature implementation details

Do one thing at a time, and does well.

Today idle Nothing, write a peer-to point of the chat function of small programs, I think the network programming Beginners learning is very useful. Apart, I'll put the code on it. There are several places to consider clearly. I'll write it back in the code. The code is at the end of the download article.

Server.c

#include <stdio.h>#include<sys/types.h>#include<sys/socket.h>#include<stdlib.h>#include<netinet/inch.h>#include<arpa/inet.h>#include<unistd.h>#include<string.h>#include<signal.h>
#defineErr_exit (M) Do{perror (M); Exit (Exit_failure); } while(0)voidDo_something (intconn) { Charrecvbuf[1024x768]; for(;;) {memset (recvbuf,0,sizeof(RECVBUF)); intret = Read (CONN,RECVBUF,sizeof(RECVBUF)); if(ret = =0) {printf ("Client closed!\n"); Break; } Else if(ret = =-1) {Err_exit ("Read"); } fputs (Recvbuf,stdout); Write (Conn,recvbuf,ret); }}voidHandlerintSIG) {printf ("recv a sig =%d\n", SIG); Exit (exit_success);}intMain () {intLISTENFD; if(LISTENFD = socket (Af_inet,sock_stream,0)) <0) Err_exit ("Socket"); intOn =1; intret = setsockopt (Listenfd,sol_socket,so_reuseaddr,&on,sizeof(on)); structsockaddr_in servaddr; memset (&AMP;SERVADDR,0,sizeof(SERVADDR)); Servaddr.sin_family=af_inet; Servaddr.sin_port= Htons (10001); Servaddr.sin_addr.s_addr=htonl (Inaddr_any); if(Bind (LISTENFD, (structsockaddr*) &servaddr,sizeof(SERVADDR)) <0) Err_exit ("Bind"); if((Listen (listenfd,somaxconn)) <0)//active sockets, becoming passive socketsErr_exit ("Listen"); structsockaddr_in peeraddr; socklen_t Socklen=sizeof(PEERADDR); intConn; pid_t pid; if(conn = Accept (LISTENFD, (structsockaddr*) (&peeraddr,&socklen)) <0)//get to be an active socketErr_exit ("Accept"); printf ("ip:%s port:%d\n", Inet_ntoa (PEERADDR.SIN_ADDR), Ntohs (Peeraddr.sin_port)); PID=Fork (); Charsendbuf[1024x768] = {0}; if(PID = =-1) Err_exit ("PID"); if(PID = =0) {signal (Sigusr1,handler); while(Fgets (SendBuf,sizeof(SENDBUF), stdin)! =NULL) {Write (Conn,sendbuf,strlen (SENDBUF)); memset (SendBuf,0,sizeof(SENDBUF)); } printf ("Child closed\n"); Exit (exit_success); } Else { Charrecvbuf[1024x768]; while(1) {memset (Recvbuf,0,sizeof(RECVBUF)); intret = Read (CONN,RECVBUF,sizeof(RECVBUF)); if(ret = =-1) Err_exit ("Read"); Else if(ret = =0) {printf ("Peer close\n"); Break; } fputs (Recvbuf,stdout); } printf ("Kill parent!\n"); Kill (PID,SIGUSR1); Exit (exit_success); //do_something (conn);} close (conn); Close (LISTENFD); Exit (0);}
#include <stdio.h>#include<sys/socket.h>#include<sys/types.h>#include<netinet/inch.h>#include<string.h>#include<unistd.h>#include<stdlib.h>#include<arpa/inet.h>#include<signal.h>#defineErr_exit (M) Do{perror (M);      Exit (Exit_failure); }  while(0)voidHandlerintSIG) {printf ("recv a sig =%d\n", SIG); Exit (exit_success);}intMainintargcChar*argv[]) {    intSOCKFD; if(SOCKFD = socket (Af_inet,sock_stream,0)) <0) Err_exit ("Socket"); structsockaddr_in servaddr; memset (&AMP;SERVADDR,0,sizeof(SERVADDR)); Servaddr.sin_family=af_inet; Servaddr.sin_port= Htons (10001); Servaddr.sin_addr.s_addr= Inet_addr ("127.0.0.1"); if(Connect (SOCKFD,structsockaddr*) &servaddr,sizeof(SERVADDR)) <0) Err_exit ("Connect"); Charsendbuf[1024x768] = {0}; Charrecvbuf[1024x768] = {0};    pid_t pid; PID=Fork (); if(PID = =-1) Err_exit ("Fork"); if(PID = =0)    {         while(1) {memset (Recvbuf,0,sizeof(RECVBUF)); intret = Read (SOCKFD,RECVBUF,sizeof(RECVBUF)); if(ret = =-1) Err_exit ("Read"); Else if(ret = =0) {printf ("Peer closed\n");  Break;        } fputs (Recvbuf,stdout); } printf ("Child close\n");        Kill (PID,SIGUSR1);    Exit (exit_success); }    Else{signal (Sigusr1,handler);  while(Fgets (SendBuf,sizeof(SENDBUF), stdin)! =NULL)              {Write (Sockfd,sendbuf,strlen (SENDBUF)); memset (SendBuf,0,sizeof(SENDBUF)); } printf ("Parent close!\n");    } close (SOCKFD); Exit (0);}

The functionality implemented is simple, but there are a few details to note:

1, C and S After the connection, when S is off, C is still not closed, I used the function of the signal.

Implementation of the method: when the parent process is closed, the child process is also closed, when the child process is closed, the parent process is also closed.

2, a thread for listening, a thread to wait for input. Well, this is a multithreaded applet.

Creates a child process. The C-side, the subprocess process listens, and the parent process waits for input. S-end opposite.

3, the problem of signal volume:

SIGUSR1: User-defined semaphore, function handler used to kill process, implementation exit.

Test of the program:

Summary: Overall, this is still very simple, that is, several functions are flexible application. Note that the read function, if not read, will enter the block, and if you receive a 0, the program is closed on behalf of the other party.

Code Download: GitHub

Statement: The level is limited, if there is any place to write wrong or understand wrong, hope that the vast numbers of netizens correct.

The realization of the chat function of Linux peer

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.