accept()没有返回不同的id(Unix域套接字)

时间:2016-04-15 20:37:02

标签: c++ unix unix-socket

#include<iostream>
#include<sys/socket.h>
#include<sys/un.h>
#include<stddef.h>
#include<fcntl.h>
#include<unistd.h>
#include<errno.h>
#include<stdio.h>
#include<stdlib.h>
#include<time.h>
using namespace std;

#define QLEN    10
#define BUFFER  100

void writer(int id,char msg[],int size)
{
    write(id,msg,size);
    return;
}
void myfunction(int myfd[], int i)
{
    char rbuff[BUFFER];
    bzero(&rbuff,BUFFER);   
    int num;
    cout<<"i is : "<<i<<" , fd is"<<myfd[i]<<endl;  
    while((num=read(myfd[i],rbuff,BUFFER))>0){
                char ch[2];
        ch[0]=rbuff[0];
                ch[1]='\0';
        int p=atoi(ch);
        writer(myfd[p],rbuff,num);
        bzero(&rbuff,BUFFER);
    }
    return;
}

int serv_listen(const char *name)
{

    int opt=1;
    struct sockaddr_un servaddr,cliaddr;    
    if(strlen(name)>=sizeof(servaddr.sun_path))
    {
        std::cerr<<"Path name is invalid"<<endl;
        return -1;
    }   


    int listenfd=socket(AF_LOCAL,SOCK_SEQPACKET,0);
       if(listenfd ==(-1))
        { 
            std::cerr<<"Error creating the socket"<<listenfd<<endl;
            return -1;  
        }

    unlink(name);
    bzero(&servaddr, sizeof(servaddr));
    servaddr.sun_family=AF_LOCAL;
    strcpy(servaddr.sun_path,name);
    if( setsockopt(listenfd, SOL_SOCKET, SO_REUSEADDR, (char *)&opt, sizeof(opt)) < 0 )
            {
                std::cerr<<"Failure"<<endl;
                exit(EXIT_FAILURE);
            }

    if(bind(listenfd,(sockaddr *) &servaddr, sizeof(servaddr))<0)
        {   
            std::cerr<<"Error binding the socket"<<endl;
            return -1;  
        }
    int connfd[3]={0};int i=0,j=0;
    if(listen(listenfd,QLEN)<0)// Telling the kernel that we are the Server
        {   
            std::cerr<<"Error in Listing to the  socket"<<endl;
            return -1;  
        }
    socklen_t len=sizeof(cliaddr);

    while(true){
              if(connfd[j]=accept(listenfd,(sockaddr *) &cliaddr,&len))
            {       cout<<"c :"<<j<<endl;
                j+=1;
                }

            /*if(j==2)
            {
                for(int k=0;k<2;k++)
                cout<<k<<": "<<connfd[k];
            }*/
        //std::cout<<endl<<"Connection fd of client number"<<i<<": "<<connfd[i];

        if(!fork()){        
            close(listenfd);
            //std::cout<<"into fork"<<connfd[i]<<endl;
            myfunction(connfd,i);
            //std::cout<<"out of myfunc"<<endl;
            close(connfd[i]);
            return 0;
        }
        close(connfd[i]);
        i++;
    }
        return(listenfd);

}

int main(void)
{
    int fd,size;    
    cout<<"Initiating Server"<<endl;
        fd=serv_listen("mysocket");
    close(fd);
    return 0;
}
  

每次将客户端连接到此服务器时,accept函数调用都会返回相同的fd。   我想在客户端(多个)之间共享消息。   但是使用相同的ID,我无法唯一地识别我的客户以在它们之间共享数据。   我已经尝试了SOCK_STREAM和SOCK_SEQPACKET,但每次都遇到同样的问题。

0 个答案:

没有答案