Design and implementation of TCP network chat room based on Linux

Source: Internet
Author: User
Tags socket error server port htons

Using Linux to implement TCP-mode-based network chat programs
The two main components are: Server and client.

    • The server program is primarily responsible for listening to messages sent by the client.
    • The client needs to log on to the server side in order to achieve normal chat functionality. The program uses processes and shared memory to send messages to the group.

The following is a simple analysis of the server-side and client two aspects of the task to be completed.

The main functions of the server are as follows:

    1. Listens on a specific port, waiting for the client to connect.
    2. The user can configure the server-side listening port.
    3. Sends logon success information to the connected client.
    4. Send a system message to a user who is already connected to the server.
    5. Send messages to all clients online using a TCP multi-threaded concurrent server

The main functions of the client are as follows:

    1. Client input IP and port number and user name to register
    2. Connect to the service side of a service that is already open
    3. Users can send information to everyone
    4. Users can accept system messages sent by the server

Server Function Description
The server is mainly responsible for listening to the message sent by the client, using the TCP thread concurrent server model to achieve the client listening and receiving.
The role of the server program is: to initialize the server program, continuously listen to a fixed port, after receiving the customer's connection to establish a socket connection, communication and information processing with the customer, receiving the customer through the socket connection sent data, create a new socket , through the socket connection with the customer communication, the response processing, and return the results, the end of the communication terminal with the customer connection (close socket); The main process is to create a shared memory space function for the server, and a simple client interface, using the socket model mechanism to implement the server simple model, Using the socket () to create a streaming socket, and can return the socket, using bind () to implement the socket with the local address, listen () to notify the TCP server ready to listen to the client's connection, accept () receive connection, waiting for the client connection, After establishing the connection, accept returns the socket of the new identity client, using multithreading and recv ()/send () to receive the sent data;

Client Function Description
The client is mainly used to send data to the server side, the role of the client program: Initialize the client program, connect to a server, establish a socket connection, send the request information to the server through the socket connection, interrupt the connection with the customer after the end of the communication. The main implementation steps are: need to define the parameters to run time, also using the socket () to establish a streaming socket, return the socket size, connect () connect the socket with the remote host, recv () and send () send and receive the read and write data on the socket, close () Close the socket and close the conversation.

C.c

#include <stdio.h>#include <netinet/in.h>#include <sys/socket.h>#include <sys/types.h> #include <string.h>#include <stdlib.h>#include <netdb.h>#include <unistd.h>#include <signal.h>#include <errno.h>#include <time.h>#define SIZE 1024x768intMainintargcChar*argv[]) {pid_t pid;intSOCKFD,CONFD;CharBuffer[size],buf[size];structSockaddr_in server_addr;structSockaddr_in client_addr;structHostent *host; ShortPortChar*name;//Four parameters    if(argc!=4)     {fprintf(stderr,"usage:%s hostname \a\n", argv[0]);Exit(1); }//Use hostname to query the host name    if((Host=gethostbyname (argv[1])) {==null) {fprintf(stderr,"GetHostName error\n");Exit(1); } port=atoi (argv[2]); name=argv[3];/ * Client starts to build SOCKFD descriptor * /     if(Sockfd=socket (Af_inet,sock_stream,0))==-1)     {fprintf(stderr,"Socket error:%s\a\n", Strerror (errno));Exit(1); }Else{printf("Socket successful!\n"); }/ * Client program fills the data on the server * /Bzero (&AMP;SERVER_ADDR,sizeof(SERVER_ADDR));//Initialize, set 0Server_addr.sin_family=af_inet;//IPV4Server_addr.sin_port=htons (port);//(Convert short data on this machine to short data on the network) port numberServer_addr.sin_addr=* ((structIN_ADDR *) host->h_addr);//IP address    / * Client initiates connection request * /     if(Confd=connect (SOCKFD, (structSOCKADDR *) (&AMP;SERVER_ADDR),sizeof(structSOCKADDR)) ==-1)     {fprintf(stderr,"Connect error:%s\a\n", Strerror (errno));Exit(1); }Else{printf("Connect successful!\n"); }/ * Send the client's name to the server side * /Send (Sockfd,name, -,0);/* Create child processes for read and write operations */PID = fork ();//Create child process      while(1)    {/ * Parent process used to send information * /           if(PID >0)           {/ * Time function * /           structTM *p;           Time (&AMP;TIMEP);           p = localtime (&AMP;TIMEP); Strftime (Buffer,sizeof(buffer),"%y/%m/%d%h:%m:%s", p);/* Output time and client's name */           strcat(Buffer,"\n\t nickname");strcat(Buffer,name);strcat(Buffer,": \n\t\t");memset(BUF,0, SIZE); Fgets (Buf,size,stdin);/ * Manage the client program * /           if(strncmp("E", BUF,1)==0)           {printf("The client is offline ... \ n");strcat(Buffer,"quit the chat room!" ");if(Send (Sockfd,buffer,size,0)) <=0) {perror ("Error Send");             } close (SOCKFD); SOCKFD =-1;Exit(0); }Else{Strncat(Buffer,buf,strlen(BUF)-1);strcat(Buffer,"\ n");if(Send (Sockfd,buffer,size,0)) <=0) {perror ("Send"); }           }        }Else if(PID = =0)        {/ * Child process for receiving information * /               memset(Buffer,0, SIZE);if(Sockfd >0)               {if(Recv (Sockfd,buffer,size,0)) <=0) {Close (SOCKFD);Exit(1); }printf("%s\n", buffer); }}} close (SOCKFD);return 0; }

S.c

#include <stdio.h>#include <stdlib.h>#include <sys/types.h>#include <sys/stat.h>#include <netinet/in.h>#include <sys/socket.h>#include <string.h>#include <unistd.h>#include <signal.h>#include <sys/ipc.h>#include <errno.h>#include <sys/shm.h>#include <time.h>#include <pthread.h>#define PORT 4395#define SIZE 1024x768#define SIZE_SHMADD 2048#define BACKLOG 3intSOCKFD;intFd[backlog];intI=0;/********* Socket Descriptor *******/intGET_SOCKFD () {structSockaddr_in server_addr;if(Sockfd=socket (Af_inet,sock_stream,0))==-1)  {fprintf(stderr,"Socket error:%s\n\a", Strerror (errno));Exit(1); }Else{printf("Socket successful!\n"); }/*SOCKADDR structure * /Bzero (&AMP;SERVER_ADDR,sizeof(structsockaddr_in));                    Server_addr.sin_family=af_inet;     Server_addr.sin_addr.s_addr=htonl (Inaddr_any); Server_addr.sin_port=htons (port);/* IP and Server port number of the binding server */    if(Bind (SOCKFD, (structSOCKADDR *) (&AMP;SERVER_ADDR),sizeof(structSOCKADDR)) ==-1)         {fprintf(stderr,"Bind error:%s\n\a", Strerror (errno));Exit(1); }Else{printf("Bind successful!\n"); }/ * Set the maximum number of clients allowed to connect * /          if(Listen (Sockfd,backlog) ==-1)          {fprintf(stderr,"Listen error:%s\n\a", Strerror (errno));Exit(1); }Else{printf("listening.....\n"); }returnSOCKFD;}/ * Create a shared storage area * /intShmid_create () {intShmid;if(Shmid = Shmget (Ipc_private,size_shmadd,0777)) <0) {perror ("Shmid error!");Exit(1); } Elseprintf("Shmid success!\n");returnShmid;}intMainintargcChar*argv[]) {CharShmadd_buffer[size_shmadd],buffer[size];structSockaddr_in client_addr;intSin_size; pid_t Ppid,pid;intNEW_FD;intShmid;Char*shmadd;/*********** shared Memory **************/Shmid = Shmid_create ();//Map Shared memoryShmadd = Shmat (Shmid,0,0);/***** Creating a Socket descriptor ***********/     intSOCKFD = GET_SOCKFD ();/ * Loop Receive client * /     while(1)    {/ * Server blocked until client program establishes a connection * /Sin_size=sizeof(structSOCKADDR_IN);if(New_fd=accept (SOCKFD, (structSOCKADDR *) (&AMP;CLIENT_ADDR), &sin_size)) ==-1)               {fprintf(stderr,"Accept error:%s\n\a", Strerror (errno));   EXIT1); }Else{printf("Accept successful!\n"); } fd[i++] = NEW_FD;printf("\ nthe client%d:%s:%d \ n" is connected, I, Inet_ntoa (client_addr.sin_addr), Ntohs (Client_addr.sin_port));/ * Send the interface to the client * /     memset(Buffer,0, SIZE);strcpy(Buffer,"\ n —————————————————— welecom come char ——————————————————————— \ n"); Send (New_fd,buffer,size,0);//Create child process clientPpid = fork ();if(Ppid = =0)    {//New customer to be added to all online clients/Recv (New_fd,buffer,size,0);strcat(Buffer,"in the chat room ..."); for(i=0; i<backlog;i++) {if(fd[i]!=-1) {Send (Fd[i],buffer,strlen(buffer),0); }              }//Create sub-processes for read/write operations/PID = fork (); while(1)       {if(PID >0)         {//parent process for receiving information/           memset(Buffer,0, SIZE);if(Recv (New_fd,buffer,size,0)) <=0) {Close (NEW_FD);Exit(1); }memset(Shmadd,0, Size_shmadd);strncpy(Shmadd, buffer, size_shmadd);//Put the client information of the buffer into the shared memory            printf("%s\n", buffer); }if(PID = =0)         {//Sub-process for sending information/Sleep1);//Execute parent process First           if(strcmp(shmadd_buffer,shmadd)! =0)           {strcpy(Shmadd_buffer,shmadd);if(New_fd >0)              {if(Send (New_fd,shmadd,strlen(Shmadd),0) == -1) {perror ("Send"); }memset(Shmadd,0, Size_shmadd);strcpy(Shmadd,shmadd_buffer); }           }         }      }     }    } Free(buffer);   Close (NEW_FD); Close (SOCKFD);return 0;}
    1. The server compiles the execution

    2. The client compiles the execution

    3. The server appears the result

    4. Also open a terminal to perform execution on client code compilation

Design and implementation of TCP network chat room based on Linux _ documentation/code

Design and implementation of TCP network chat room based on Linux

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.