Socket chat room (server side) (multithreading) (TCP)

Source: Internet
Author: User
Tags strcmp types of functions

#include <string.h>#include<signal.h>#include<stdio.h>#include<sys/socket.h>#include<stdlib.h>#include<netdb.h>#include<pthread.h>#include<memory.h>#include<semaphore.h>intthread_num=0, count=0;//define client counters, write thread countersintsockfd;sem_t sem,sem2; pthread_mutex_t tmutex,cmutex;pthread_attr_t pattr; Define the thread properties to createvoidCt_thread (Char* ARG,intACPFD);Charchatct[1024x768]; Define Chat CachevoidGet_sys_time (Char*tbuf)//function function: Get the current system time and crop {LongT=time (0); Char*stime=ctime (&t); intI= One; tbuf[0]='(';  for(;i< -; i++) Tbuf[i-Ten]=Stime[i]; Tbuf[i- One]=')'; Tbuf[i-Ten]=' /';}void* Do_read (void*Arg) //function: Read thread for receiving information from client, save to buffer
{ intAcfd= (int) Arg; Chartimeb[ -];//Char name[7];//memset (name,0,sizeof (name));//Read (acfd,name,sizeof (name));//name[sizeof (name) -1]= ' + ';//puts (name); while(1) { intret; Charbuf[1024x768]; memset (BUF,0,sizeof(BUF)); RET=read (Acfd,buf,sizeof(BUF)); Sem_wait (&sem2); if(ret<0) {perror ("Do_read Errro"); Continue; } Else if(ret==0) {close (ACFD); Sem_post (&sem2); printf ("a person exit\n"); Break; } Else{memset (Timeb,0,sizeof(TIMEB));//strcpy (chatct,name);//puts (CHATCT);//strcat (CHATCT, ":");//puts (CHATCT);Get_sys_time (TIMEB); strcpy (CHATCT,BUF); strcat (CHATCT,TIMEB);//puts (CHATCT); //printf ("Do_read%lu\n", pthread_self ());Sem_post (&SEM); } //puts (CHATCT); } return(void*)0;}void* Do_write (void*arg)//function: A write thread that sends the data of the buffer to each client that is connected, emptying the buffer when all the clients receive the message. { intFd= (int) Arg; while(1) {sem_wait (&SEM); if(Write (FD,CHATCT,sizeof(CHATCT)) <0) {Thread_num--; if(count==thread_num) {memset (CHATCT,0,sizeof(CHATCT)); Pthread_mutex_lock (&CMutex); Count=0; Pthread_mutex_unlock (&CMutex); Sem_post (&sem2); } Else if(count<thread_num) {Sem_post (&SEM); } close (FD); Break; } Else{Pthread_mutex_lock (&CMutex); Count++; Pthread_mutex_unlock (&CMutex); } if(count<thread_num) {Sem_post (&SEM); Usleep (1); } Else if(count==thread_num) {memset (CHATCT,0,sizeof(CHATCT)); Pthread_mutex_lock (&CMutex); Count=0; Pthread_mutex_unlock (&CMutex); Sem_post (&sem2); } } return(void*)0;}voidDo_thread (intACPFD)//function function: Create a read thread for each client connected to it, a write thread {//char* start= "------------------welcome my chatroom--------------------\ n";//Write (Acpfd,start,strlen (start));Pthread_mutex_lock (&CMutex); Thread_num++; Count the number of threads per creation plus 1 Pthread_mutex_unlock (&CMutex); Ct_thread ("Read", ACPFD); Ct_thread ("Write", ACPFD);}voidCt_thread (Char* ARG,intACPFD)//function function, different types of functions are created depending on the parameters of the pass. {pthread_t pt;/*if (!strcmp (ARG, "create")) {if (Pthread_create (&PT,&PATTR,THREAD_CT, (void*) ACPFD) <0) { Perror ("Thread creat error"); Exit (1); } }*/Create threads in isolation to prevent resources from being recycledif(!STRCMP (ARG,"Read")) { if(Pthread_create (&pt,&pattr,do_read, (void*) ACPFD) <0) {perror ("Thread creat error"); Exit (1); } } Else if(!STRCMP (ARG,"Write")) { if(Pthread_create (&pt,&pattr,do_write, (void*) ACPFD) <0) {perror ("Thread creat error"); Exit (1); } }}voidMysighand (intsigno)//function: When the program ends, processes the returned signal, releasing the resource {if(signo==SIGINT) {printf ("Server close!\n"); Close (SOCKFD); Sem_destroy (&SEM); Sem_destroy (&sem2); Pthread_mutex_destroy (&CMutex); Pthread_mutex_destroy (&Tmutex); Pthread_attr_destroy (&pattr); Exit (1); }}intMainintargcChar*argv[]) { if(argc<2) {perror ("ARGC Error"); Exit (1); } if(Signal (sigint,mysighand) = =sig_err)//Register signal processing function {perror ("Signal Error"); Exit (1); }
/* 1 Initialize Sem_init (&sem,0,0); Sem_init (&AMP;SEM2,0,1); Pthread_mutex_init (&tmutex,null); Pthread_mutex_init (&cmutex,null); Pthread_attr_init (&pattr);
*/
  if(Pthread_attr_setdetachstate (&pattr,pthread_create_detached) <0)//Set Detach property {perror ("setdetached Error"); Exit (1); } memset (CHATCT,0,sizeof(CHATCT)); Initializing the buffer sockfd=socket (Af_inet,sock_stream,0);//Create a socket in TCP modeif(sockfd<0) {perror ("SOCKFD Error"); Exit (1); } structsockaddr_in ser; Ser.sin_family=af_inet; IP type: IPV4 ser.sin_port=htons (Atoi (argv[1])); Host byte order converted to network byte order ser.sin_addr.s_addr=Inaddr_any; Host all reachable IPsif(Bind (SOCKFD, (structsockaddr*) &ser,sizeof(Ser)) <0)//socket and IP bindings {perror ("bind error"); Exit (1); } if(Listen (SOCKFD,Ten) <0)//Listener waiting for client connection {perror ("Listen error"); Exit (1); } while(1) { intACPFD; if((Acpfd=accept (sockfd,null,null)) <0)//Handle the client on each connection, and if there is no client connection, block Break; Else{do_thread (ACPFD);//Execute Processing connection function}}return 0;}

The main idea of the service side:

Create a read thread and a write thread for each client that is connected (detach state-initiated thread, thread to self-recycle), server-to-client communication is actually a multi-reader-writer model (using semaphores and client counters, thread counters, threads synchronization and mutual exclusion)

The difference is that when the client disconnects, the server should change the client counter and handle the logic in time.

Servers run on the cloud server, and the client can be implemented with QT or Android.

Insufficient points:

It's just anonymous chat. Simple function. Just show the chat content and the time the data was sent

Advantages:

Can support a large number of clients to connect at the same time. And the data does not go wrong when the network speed is unhealthy (non-network error in Channel pass )

Socket chat room (server side) (multithreading) (TCP)

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.