Linux socket通信(多线程Linux socket通信(TCP))

#include <stdio.h>
#include <sys/socket.h>
#include <string.h>
#include <arpa/inet.h>
#include <unistd.h>
#include <netinet/in.h>
#include <pthread.h>
#include <string.h>
#define TCP_PORT 9999

struct thinfo
{
    int tid;
    struct sockaddr_in addrinfo;
};

void* doThing(void *argv)
{

    char recbuf[0x1000];
    char ipbuf[32];
    thinfo *Thininfo = (thinfo*)argv;
    bzero(recbuf,sizeof(recbuf));
    bzero(ipbuf, sizeof(ipbuf));
    inet_ntop(AF_INET,&Thininfo->addrinfo.sin_addr.s_addr,ipbuf,sizeof(ipbuf));
    printf("Threadid is %d ,Ip is %s,port is %d\n",pthread_self(), ipbuf,ntohs(Thininfo->addrinfo.sin_port));
    int len = read(Thininfo->tid,recbuf,sizeof(recbuf));
    printf("%s\n",recbuf);
    write(Thininfo->tid,recbuf,len);
    close(Thininfo->tid);
    return 0;

}


int main()
{


    pid_t pid;
    int socket_ser,socket_accept;
    socket_ser = socket(AF_INET,SOCK_STREAM,0);
    struct sockaddr_in addr,addr_c;
    bzero(&addr,sizeof(addr));
    addr.sin_family = AF_INET;
    addr.sin_port = htons(TCP_PORT);
    addr.sin_addr.s_addr = htonl(INADDR_ANY);
    bind(socket_ser,(struct sockaddr *)&addr,sizeof(addr));
    listen(socket_ser,128);
    while(1)
    {

        bzero(&addr_c,sizeof(addr_c));

        int len_c;
        socket_accept = accept(socket_ser,(struct sockaddr *)&addr_c,(socklen_t *)&len_c);
        pthread_attr_t attr;
        pthread_attr_init(&attr);
        pthread_attr_setdetachstate(&attr,PTHREAD_CREATE_DETACHED);
        pthread_t pthread;
        thinfo *Thinginfo = new thinfo;
        memcpy(&Thinginfo->addrinfo,&addr_c,sizeof(addr_c));
        Thinginfo->tid = socket_accept;
        //设置分离属性
        pthread_create(&pthread,&attr,doThing,(void*)Thinginfo);

    }
    close(socket_ser);
    return 0;
}

记得设置线程的分离属性,或者在线程函数中调用pthread_detach函数。

listen只是创建监听套接字,3路握手并不是由listen函数来完成的。
listen只做两件事:
1,将socket创建的主动(默认)套接字转换成被动套接字,指示内核接受指向该套接字的连接请求
2,指定内核应该为相应套接字排队的最大连接数
accept仅仅是从监听套接字队列中取出完成握手的连接套接字,至于阻塞的唤醒也是由内核自动完成的
accept取出套接字的队列存放的全是已经完成连接的套接字,对于监听套接字,一般会有两个队列,未完成连接套接字和已完成连接套接字,当请求到达时,新建套接字会被存放在未完成中,3路握手完毕就会被转移到已完成队列里,accept就是从已完成队列里取。这两个队列的维护和3路握手都

猜你喜欢

转载自blog.csdn.net/woshichaoren1/article/details/85462928