The Pthread_exit () function can call the end of this thread directly within the line function.
You begin by initializing a pthread_t Thread_fd[max] array to store the open threads, and then use a stack to store the index of the Unassigned array elements (thread_fd[index]=0).
Server side:
#include <stdlib.h> 8 #include <pthread.h> 9 #include <sys/socket.h> #include <sys/types.h>
pthread_t, pthread_attr_t and so on. #include <stdio.h> #include <netinet/in.h>//structure sockaddr_in #include <arpa/inet.h> func:htonl; htons; Ntohl; Ntohs #include <assert.h>//func:assert #include <string.h>//func:memset #inclu de<unistd.h>//func:close,write,read #define SOCK_PORT 9988 #define BUFFER_LENGTH 1024 #define Max_conn_limit//max connection LIMIT static void Data_handle (void * sock_fd);
Only can is seen in the file int main () {int sockfd_server;
-int sockfd;
int fd_temp;
struct sockaddr_in s_addr_in;
struct sockaddr_in s_addr_client;
int client_length; Sockfd_server = socket (af_inet,sock_stream,0); Ipv4,tcp assert (Sockfd_server!=-1);
//before bind (), set the attr of structure sockaddr.
memset (&s_addr_in,0,sizeof (s_addr_in));
Panax Notoginseng s_addr_in.sin_family = af_inet; S_ADDR_IN.SIN_ADDR.S_ADDR = htonl (Inaddr_any);
Trans addr from uint32_t host byte to network byte order. S_addr_in.sin_port = htons (Sock_port);
Trans Port from uint16_t host byte to network byte order.
Fd_temp = bind (sockfd_server, struct scokaddr *) (&s_addr_in), sizeof (s_addr_in));
if (fd_temp = = 1) fprintf (stderr, "bind error!\n");
The exit (1);
Fd_temp = Listen (Sockfd_server,max_conn_limit);
if (fd_temp = = 1) fprintf (stderr, "Listen error!\n");
Wuyi exit (1);
(1) ("Waiting for New connection...\n");
pthread_t thread_id;
client_length = sizeof (s_addr_client); //block here. Until SERVer accpets a new connection.
SOCKFD = Accept (Sockfd_server, (struct sockaddr_*) (&s_addr_client), (socklen_t *) (&client_length));
if (sockfd = = 1) fprintf (stderr, "Accept error!\n"); Continue;
Ignore current socket, continue while loop.
("A New Connection occurs!\n"); Pthread_create (&thread_id,null, (void *) (&data_handle), (void *) (&SOCKFD) = = 1) 69 {7
0 fprintf (stderr, "Pthread_create error!\n"); a break; Break-While loop-n-//clear-INT ret = shutdown (SOCKFD_SERVER,SHUT_WR);
Shut down the "all" or part of a Full-duplex connection.
The ASSERT (Ret!=-1);
down\n printf ("Server shuts");
0; Data_handle (void * sock_fd) $ {= Int FD = * (int *) SOCK_FD);
i_recvbytes int;
Data_recv[buffer_length Char];
The const char * data_send = "Server has received your request!\n";
(1) ("Waiting for request...\n");
//reset data.
memset (data_recv,0,buffer_length);
I_recvbytes = Read (fd,data_recv,buffer_length); (i_recvbytes = 0) ("Maybe the client has closed\n"); Bre
Ak 102 if (i_recvbytes = = 1) fprintf (stderr, "read error!\n"); 105
Break strcmp (DATA_RECV, "quit") ==0) 108 {109 printf ("Quit command!\n"