实现TCP并发服务器:多线程方式

1.前言

1.1声明

文章中的文字可能存在语法错语以及标点错误,请谅解;

如果在文章中发现代码错误或其它问题请告知,感谢!

文章中的程序为示例程序,在项目应用中若需考虑到全局变量,则要增加互斥锁,信号量等方式保证程序的正常运行,并且每一个变量都要赋初值,每一个函数的返回值都要打印printf,以便调试。

2.代码实现

服务器端:

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#include <sys/types.h>
#include <netdb.h>
#include <sys/ioctl.h>
#include <net/if.h>
#include <pthread.h>
#include <errno.h>

#define LISTENQ 5
#define PORT 5000

void *ReadMesg(void *arg)
{
    int fd = *((int *)arg);
    int nread = 0;
    char buffer[1024];
    while((nread = read(fd,buffer,sizeof(buffer))) > 0)
    {
        buffer[nread] = '\0';
        printf("get client message: %s\n",buffer);
        memset(buffer,0,sizeof(buffer));
    }

    return NULL;
}

int main()
{
    int listenfd,connfd;
    int ret;
    pthread_t tid;
    socklen_t clilen;
    struct sockaddr_in cliaddr,servaddr;

    clilen = sizeof(cliaddr);

    listenfd = socket(AF_INET,SOCK_STREAM,0);

    bzero(&servaddr,sizeof(servaddr));
    servaddr.sin_family = AF_INET;
    servaddr.sin_addr.s_addr = htonl(INADDR_ANY);
    servaddr.sin_port = htons(PORT);

    bind(listenfd,(struct sockaddr*)&servaddr,sizeof(servaddr));
    listen(listenfd,LISTENQ);

    while(1)
    {
        connfd = accept(listenfd,(struct sockaddr*)&cliaddr,&clilen);
        if(connfd < 0)
        {
            perror("accept failed!");
        }

        ret = pthread_create(&tid,NULL,(void*)&ReadMesg,(void*)&connfd);
        if(0 != ret)
        {
            perror("create thread erro!");
        }
    }
    close(listenfd);
    exit(0);
}

客户端:

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#include <sys/types.h>
#include <netdb.h>
#include <sys/ioctl.h>
#include <net/if.h>
#include <pthread.h>
#include <errno.h>

#define LISTENQ 5
#define PORT 5000
#define ServerIP "192.168.237.131"

int main()
{
    int sendfd;
    int ret;
    int sendnum;
    char sendbuf[4096];
    pthread_t tid;
    struct sockaddr_in servaddr;

    sendfd = socket(AF_INET,SOCK_STREAM,0);

    bzero(&servaddr,sizeof(servaddr));
    servaddr.sin_family = AF_INET;
    servaddr.sin_addr.s_addr = inet_addr(ServerIP);
    servaddr.sin_port = htons(PORT);

    connect(sendfd,(struct sockaddr *)&servaddr,sizeof(struct sockaddr));
    while(1)
    {
        printf("Input Mesg:");
        scanf("%s",sendbuf);
        sendnum = send(sendfd,sendbuf,strlen(sendbuf),0);
        if(sendnum < 0)
        {
            perror("send erro");
            exit(1);
        }
    }
    close(sendfd);
    exit(0);
}

源代码的github下载地址:
https://github.com/fyw4/Linux-C-TCP
参考资料:
https://blog.csdn.net/ciaos/article/details/7711176

猜你喜欢

转载自blog.csdn.net/wangqingchuan92/article/details/80596718