2014-03-05 52 views
2

我必須將fgets的輸出連接到intclientid),並將其存儲在char[1024]緩衝區中。String and int concatination

這裏是我的代碼:

clientid = rand() % 256; 



while(1) 
{ 
    cout<<"Client: Enter Data for Client="; 

    fgets(buffer,MAXSIZE-1,stdin); 

    if((send(sockfd,buffer,strlen(buffer),0))==-1) 
    { 
     cout<<"Failure Sending Message"; 
     close(sockfd); 
     exit(1); 
    } 
    else 
    { 
     cout<<"Client:Message being sent:"<<buffer; 
     num=recv(sockfd,buffer,sizeof(buffer),0); 
     if(num<=0) 
     { 
      cout<<"either connection close or Error"; 
      break; 
     } 
     buffer[num]='\0'; 
     cout<<"Client:message received from Server:"<<buffer<<endl; 
    } 
} 

close(sockfd); 
return 0; 

我怎樣才能提取clientid從服務器端的消息?

+0

一個建議開始使用的std :: string ......一定會節省大量的精力 – HadeS

回答

1

您可以將其添加到緩衝區本身的開頭。例如,如果你的客戶端是123,那麼你可以發送「123:消息」,其中「:」可以作爲分隔符。這意味着你應該在緩衝區中讀取那些數字,而不是從頭開始。

snprintf (buffer, sizeof(buffer), "%d:", clientid); // Add the clientid at the beginning before reading 
fgets(buffer + strlen (buffer),MAXSIZE-1,stdin);// Move by the len of buffer which contains clientid 
+0

感謝它是工作...ü將請告訴我如何從服務器總消息客戶端ID識別側? – user3381955

1

可以通過使用的strcat()方法,如下所示連接具有的clientId消息,

strcat(buffer, clientid); 

在服務器端,可以通過從緩衝器爲選擇的子標識的clientid下面,

std::string str=buffer; 

    std::string str2 = str.substr (messagelength,lastindex); 
相關問題