Linux Network programming (multiplayer online chat system)

Source: Internet
Author: User
Tags server port

First, the establishment of the server

The first is a signal termination program, send the signal CTRL + C to terminate the program, but is to initialize network communication.

Creates a descriptor that is responsible for binding the server and listening to the message that the server receives the client.

Socket ()->sockaddr_in->bind->listen (Ready)

Begins receiving client messages. Start () function

The first is to declare a message that the struct is used to store the client, and use the Accept () function to create a new

Descriptor to receive, there is blocking effect, that is to say that the connection can only be one-to-one.

The separation thread then handles the SOCKFD connection.

Pthread_create (&PID,0,PTHREAD_DEAL,&SOCKFD1);

Threads are mainly the separation of threads first, then the SOCKFD descriptor that obtains them, the information of this client

stored in an array of structs. Then the call loop sends the function to each client to send the message.

When the receive function recv (sockfd,buf,sizeof (buf)) = = 0, indicating that there is a client exit, this time

Just set the corresponding FD in the struct array to 0.

#include"Server.h"#include<sys/socket.h>#include<arpa/inet.h>#include<netinet/inch.h>intSOCKFD;//descriptor for the server itselfstructUser u[ $] = {};//information to save the userintSize//The subscript of the array, and also the number of clientsvoidInitvoid)//Communications Preparation Work{printf ("Chat room server starts now ... \ n"); SOCKFD= Socket (Af_inet,sock_stream,0); if(-1==sockfd) {Perror ("fail to socket"); printf ("Server Failure!\n"); Exit (-1); }    //preparing the communication address and binding server    structsockaddr_in addr; Addr.sin_family=af_inet; Addr.sin_port= Htons (2222);//The value of the port, converted into a network formatADDR.SIN_ADDR.S_ADDR = inet_addr ("172.16.1.21"); if(-1= = Bind (SOCKFD, (structsockaddr*) &addr,sizeof(addr))) {Perror ("fail to bind"); Exit (-1); } printf ("bind is OK, welcome to visit!\n"); //Setting up monitoring    if(-1! = Listen (SOCKFD, $) {printf ("monitoring is set up, everything is ready!\n"); }}voidSend_msg (Char*P_MSG)//functions for sending messages{    intnum =0;  for(num =0; Num < size;num++)    {        if(U[NUM].FD)//if it's valid, send it.{Send (u[num].fd,p_msg,sizeof(p_msg),0); }    }}void* Pthread_deal (void* p)//thread-handling functions{Pthread_detach (pthread_self ()); intFD2 = * (int*) p;//get the SOCKFD of the clientU[SIZE].FD = FD2;//put into the structure body    Charname[ -] = {}; intres = recv (Fd2,name,sizeof(name),0); if(Res >0) {strcpy (u[size].name,name);//Store User name} size++; Charuser[ -] = {}; sprintf (User,"%s is quietly coming in! (*^__^*) hehe ... \ n", name);    Send_msg (user);  while(1)    {        if(Recv (Fd2,name,sizeof(name),0) ==0)/*returning 0 indicates that a client exited*/{u[size-1].FD =0;//Replace the exit client's struct descriptor with 0        }    }}voidStartvoid) {printf ("success to start Server,let ' s go!\n");  while(1)    {        structSOCKADDR_IN client;//Store the information received by the clientsocklen_t length =sizeof(client); //receive client information, there will be blocking effect, SOCKFD1 tag client        intSockfd1 = Accept (SOCKFD, (structsockaddr*) &client,&length); if(Sockfd1 = =-1) {perror ("fail to accept!"); Continue;//Continue connection} printf ("%s is connected. \ n", Inet_ntoa (CLIENT.SIN_ADDR)); /*After the connection is successful, the thread is started*/pthread_t pid;//Thread IDPthread_create (&pid,0,pthread_deal,&sockfd1); }}voidSig_exit (intSigno)//sub-defined signal shutdown server function{Close (SOCKFD);//shutting down the server portprintf"server successfully shut down!\n"); Exit (0);}intMainvoid) {printf ("Press CTRL + C to close the chat room server!\n");    Signal (SIGINT,SIG_EXIT); Init ();//initialization, server communication readinessStart ();//Start the service (Start processing chat information)    return 0;}

2. Writing the client.

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.