Linux _多线程并发服务TCP
client1.c
#include <sys/types.h>
#include <sys/socket.h>
#include <sys/stat.h>
#include <sys/un.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <fcntl.h>
#include <stdlib.h>
#include <stdio.h>
#include <errno.h>
#include <signal.h>
#include <string.h>
#define BUFF_SIZE 1024
int main(void)
{
int sockfd;
struct sockaddr_in server_addr;
int ret;
int pd;
char buff[BUFF_SIZE];
sockfd = socket (AF_INET, SOCK_STREAM, 0);
server_addr.sin_addr.s_addr = inet_addr("10.10.0.9");
server_addr.sin_family = AF_INET;
server_addr.sin_port = htons(9000);
ret = connect(sockfd, (struct sockaddr*)&server_addr, sizeof(server_addr));
if (ret == -1) {
perror("connect");
exit(errno);
}
strcpy(buff, "hello");
ret = write(sockfd, buff, strlen(buff)+1);
if (ret == -1) {
perror("client write");
exit(errno);
}
ret = read(sockfd, buff, sizeof(buff));
if (ret == -1) {
perror("client read");
exit(errno);
}
printf("%s\n", buff);
exit(0);
}
server1.c
#include <sys/types.h>
#include <sys/socket.h>
#include <sys/stat.h>
#include <sys/un.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <fcntl.h>
#include <stdlib.h>
#include <stdio.h>
#include <errno.h>
#include <signal.h>
#define BUFF_SIZE 1024
//–Ë∂‘∏√»´æ÷±‰¡øΩ¯––ª•≥‚±£ª§,ªÚΩ¯––◊™¥¢°£
struct sockaddr_in client_addr;
int clientfd;
static void str2up(char *p)
{
while (*p) {
if (*p >= 'a' && *p <= 'z') {
*p = *p - 'a' + 'A';
}
p++;
}
}
static void * client_thread_handle(void *arg)
{
char buff[BUFF_SIZE];
char tmp[100];
int fd = clientfd;
int ret;
ret = read(fd, buff, sizeof(buff));
if (ret==-1) {
perror("read");
exit(1);
}
str2up(buff);
sprintf(tmp, "-thread(%u)", pthread_self());
strcat(buff, tmp);
ret = write(fd, buff, strlen(buff)+1);
if (ret == -1) {
perror("write");
exit(1);
}
sleep(3);
pthread_exit(0);
}
int main(void)
{
int sockfd;
struct sockaddr_in server_addr;
int ret;
int pd;
socklen_t len;
pthread_t pt;
sockfd = socket (AF_INET, SOCK_STREAM, 0);
server_addr.sin_addr.s_addr = htons(INADDR_ANY);
server_addr.sin_family = AF_INET;
server_addr.sin_port = htons(9000);
/* π∂Àø⁄ø…÷ÿ∏¥∞Û∂® */
int on = 1;
int ret_val;
ret_val = setsockopt(sockfd, SOL_SOCKET, SO_REUSEADDR, &on, sizeof(on));
if(ret_val < 0) {
perror("setsockopt SO_REUSEADDR");
exit(1);
}
ret = bind(sockfd, (struct sockaddr*)&server_addr, sizeof(server_addr));
if (ret == -1) {
perror("bind");
exit(errno);
}
ret = listen(sockfd, 5);
if (ret == -1) {
perror("listen");
exit(errno);
}
while (1) {
clientfd = accept(sockfd, (struct sockaddr*)&client_addr, &len);
if (clientfd == -1) {
perror("accept");
//exit(errno);
continue;
}
/* –Ë“™∂ÓÕ‚∂‘clientfdΩ¯––ª•≥‚±£ª§ªÚ’flΩ¯––◊™¥¢ */
ret = pthread_create(&pt, 0, client_thread_handle, 0);
if (ret == -1) {
perror("pthread_create");
//exit(errno);
continue;
}
pthread_detach(pt);
}
exit(0);
}