#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
# define MAXBUF 1024
Void * conClient (int new_fd);
The static char buf [MAXBUF + 1];
Int main (int arg c, char * argv [])
{
Socklen_t len.
Int pid;
Int sockfd, new_fd;
Struct sockaddr_in my_addr their_addr;
Unsigned int myport lisnum;
//char buf [MAXBUF + 1];
If (argv [2])
Myport=atoi (argv [2]);
The else
Myport=8088;
If (argv [3])
Lisnum=atoi (argv [3]);
The else
Lisnum=5;
If ((sockfd=socket (AF_INET SOCK_STREAM, 0))==1)
{
Perror (" socket ");
The exit (EXIT_FAILURE);
}
Bzero (& amp; My_addr, sizeof (my_addr));
My_addr. Sin_family=AF_INET;
My_addr. Sin_port=htons (myport);
If (argv [1])
My_addr. Sin_addr. S_addr=inet_addr (argv [1]).
The else
My_addr. Sin_addr. S_addr=INADDR_ANY;
If (bind (sockfd, (struct sockaddr *) & amp; My_addr, sizeof (struct sockaddr))==1)
{
Perror (" bind ");
The exit (EXIT_FAILURE);
}
If (listen (sockfd, lisnum)==1)
{
Perror (" listen ");
The exit (EXIT_FAILURE);
}
While (1)
{
Pthread_t con;
Printf (" wait for the connect! \n");
Len=sizeof (struct sockaddr);
If ((new_fd=accept (sockfd, (struct sockaddr *) & amp; Their_addr, & amp; Len))==1)
{
Perror (" accept ");
The exit (EXIT_FAILURE);
}
The else
{
Printf (" server: got connection from % s, port % d, socket % d \ n ", inet_ntoa (their_addr. Sin_addr), ntohs (their_addr. Sin_port), new_fd);
If (pthread_create (& amp; Con, NULL, conClient (new_fd), (void *) new_fd)==1)
{
Printf (" error ");
}
}
Printf (" newfd=% d \ n ", new_fd);
if(! Strncasecmp (buf, "quit", 4))
{
Printf (" I will close the connect! \n");
break;
}
}
Close (sockfd);
}
Void * conClient (int new_fd) {
Char * buf1="wlecome Like QQ";
Strcpy (buf, buf1);
Pthread_detach (pthread_self ());
Int len.
While (1)
{
Printf (" % s \ n ", buf);
Len=send (new_fd, buf, strlen (buf), 0).
If (len> 0)
{
Printf (" the message: % s \ t send sucessful, the send % dbyte! \ n ", buf, len);
Bzero (buf MAXBUF + 1);
}
The else
{
Printf (" the message '% s' send a failure! Errno code is % d, errno message is' % s' \ n ", buf, errno, strerror (errno));
break;
}
Len=recv (new_fd, buf, MAXBUF, 0);
If (len> 0)
Printf (" the message recv successful: '% s', % dByte recv successful:' % s', % dByte recv \ n ", buf, len);
The else
{
If (len<0)
Printf (" recv failure! Errno code is % d, errno message is' % s' \ n ", errno, strerror (errno));
The else
Printf (" the other one close the quit \ n ");
break;
}
}
Close (new_fd);
Pthread_exit (NULL);
}

CodePudding user response:
