Home > other >  Linux socket multithreaded issues
Linux socket multithreaded issues

Time:10-14

 # include & lt; Iostream> 
#include
#include
#include
#include
#include
#include
#include
#include
#include

# define SERVPORT 8000

Struct s_cliinfo {
Int connfd;
Struct sockaddr_in cliaddr;
};

Void process_cli (int fd, struct sockaddr_in cliaddr)
{
Char recvbuff [1024].
Struct MSGHDR MSG.
Struct iovec IO;
IO. Iov_base=recvbuff;
IO. Iov_len=1024;
MSG. Msg_name=& amp; Cliaddr;
MSG. Msg_namelen=sizeof (cliaddr);
MSG. Msg_iov=& amp; io;
MSG. Msg_iovlen=1;
MSG. Msg_control=NULL;
MSG. Msg_controllen=0;
MSG. Msg_flags=0;

The recvmsg (fd, & amp; MSG, 0);

STD: : cout<" The Data from the client: \ n "& lt; <(char *) MSG. Msg_iov - & gt; Iov_base & lt; Close (fd);
}

Void * start_routine (void * cliinfo)
{
Pthread_detach (pthread_self ());

Int connfd;
Char recvbuff [1024].
Struct MSGHDR MSG.
S_cliinfo * clidata;
Struct sockaddr_in cliaddr;

Cliinfo clidata=https://bbs.csdn.net/topics/(s_cliinfo *);
Connfd=clidata - & gt; Connfd;
Cliaddr=clidata - & gt; Cliaddr;
Process_cli (connfd, cliaddr);
Free (clidata);
Return 0;
}

Void the start_server ()
{
Int connfd;
Int listenfd;
Socklen_t addrlen;
S_cliinfo * cliinfo;
Pthread_t sock_handle_thread;

Struct sockaddr_in cliaddr;
Struct sockaddr_in servaddr;

Memset (& amp; Cliaddr, 0, sizeof (cliaddr));
Memset (& amp; Servaddr, 0, sizeof (servaddr));

Servaddr. Sin_family=AF_INET;
Servaddr. Sin_port=htons (SERVPORT);
Servaddr. Sin_addr. S_addr=INADDR_ANY;

If ((listenfd=socket (AF_INET SOCK_STREAM, 0)) & lt; 0 {
STD: : cout<" To create a socket! \n";
The exit (1);
}

Int opt=SO_REUSEADDR;
The setsockopt (listenfd, SOL_SOCKET, SO_REUSEADDR, & amp; Opt, sizeof (opt));
If (bind (listenfd, const struct sockaddr *) & amp; Servaddr, sizeof (servaddr)) & lt; 0 {
STD: : cout<" The Function to bind () ERROR! \n";
The exit (1);
}

If (listen (listenfd, 1024) & lt; 0 {
STD: : cout<" The Function listen () ERROR! \n";
The exit (1);
}

The addrlen=sizeof (cliaddr);
For (;;; ) {
If ((connfd=accept (listenfd, (struct sockaddr *) & amp; Cliaddr, & amp; Addrlen) & lt; 0 {
STD: : cout<" The Function the accept () ERROR! \n";
The exit (1);
}

Cliinfo=(s_cliinfo *) malloc (sizeof (s_cliinfo));
If (cliinfo==NULL) {
STD: : cout<" The Function malloc () ERROR! \n";
The exit (1);
}

Cliinfo - & gt; Connfd=connfd;
Memcpy (& amp; (cliinfo - & gt; Cliaddr), & amp; Cliaddr, sizeof (cliaddr));

If (pthread_create (& amp; Sock_handle_thread, NULL, start_routine, (void *) cliinfo)) {
STD: : cout<" The Function pthread_create () ERROR! \n";
The exit (1);
}
}
Close (listenfd);
return ;
}

Int main ()
{
The start_server ();
Return 0;
}

why use browser to access once he returned to 10 times the HTTP request!
  • Related