socket编程创建可连接多个客户端的服务器

多进程代码

#include
#include
#include                                                              
#include
#include
#include
#include
#include
#include
#include
#include
#define SERPORT 8000
#define SERIP "IP地址"


int main(int argc, char* argv[])
{
    int lfd = socket(AF_INET,SOCK_STREAM,0);

    struct sockaddr_in seraddr,cliaddr;
    seraddr.sin_family = AF_INET;
    seraddr.sin_port = htons(SERPORT);
    int dst;
    inet_pton(AF_INET,SERIP,(void*)&dst);
    seraddr.sin_addr.s_addr = dst ;

    int ret = bind(lfd,(struct sockaddr*)&seraddr,sizeof(seraddr));
    listen(lfd,64);

    socklen_t addrlen = sizeof(cliaddr);
    while(1){

    int cfd = accept(lfd,(struct sockaddr*)&cliaddr,&addrlen);
    //网络字节序整形IP地址转化成一个本地字节序点分十进制的字符窜IP
    char clip[32];
    inet_ntop(AF_INET,&cliaddr.sin_addr,clip,sizeof(clip));
    printf("clien IP=%s,PORT=%d connect ok\n",clip,ntohs(cliaddr.sin_port));
    int pid = fork();
    if(pid==0){
    char buf[1024];
       while(1){
           int rr = read(cfd,buf,sizeof(buf));
           write(STDOUT_FILENO,buf,rr);
           write(cfd,buf,rr);
       }
    }
        }

    return 0;
}

多线程代码:

#include
#include
#include                                                              
#include
#include
#include
#include
#include
#include
#include
#include
#define SERPORT 8000
#define SERIP "IP地址"

void* comm(void* arg){
    int cfd = (int)arg;
    char buf[1024];
    int rr = read(cfd,buf,sizeof(buf));
       while(1){
           write(STDOUT_FILENO,buf,rr);
           write(cfd,buf,rr);
       }
}
int main(int argc, char* argv[])
{
    int lfd = socket(AF_INET,SOCK_STREAM,0);

    struct sockaddr_in seraddr,cliaddr;
    seraddr.sin_family = AF_INET;
    seraddr.sin_port = htons(SERPORT);
    int dst;
    inet_pton(AF_INET,SERIP,(void*)&dst);
    seraddr.sin_addr.s_addr = dst ;

    int ret = bind(lfd,(struct sockaddr*)&seraddr,sizeof(seraddr));
    listen(lfd,64);

    socklen_t addrlen = sizeof(cliaddr);
    while(1){
    int cfd = accept(lfd,(struct sockaddr*)&cliaddr,&addrlen);
    pthread_t tid;
    pthread_create(&tid, NULL, comm, (void*)cfd);
    //网络字节序整形IP地址转化成一个本地字节序点分十进制的字符窜IP
    char clip[32];
    inet_ntop(AF_INET,&cliaddr.sin_addr,clip,sizeof(clip));
    printf("clien IP=%s,PORT=%d connect ok\n",clip,ntohs(cliaddr.sin_port));
    }
    return 0;
}

你可能感兴趣的:(linux网络编程,信息与通信,linux,网络,物联网)