我有下一個代碼:
while(1) {
int length=sizeof(client);
connSock=accept(readSock, (struct sockaddr*) &client,&length);
if(!fork())
{
close(readSock);
char receiveBuff[1000],sendBuff[1000];
int status;
int size_buf;
do {
status=recv(connSock, receiveBuff, 1000,0);
printf("%d status \n",status);
printf("%s recv buff\n", receiveBuff);
memcpy(sendBuff,receiveBuff,sizeof(receiveBuff));
send(connSock, &sendBuff, sizeof(sendBuff), 0);
}while (status!=0);
close(connSock);
exit(0);
}
close(connSock);
}
我正在嘗試發送訊息"Test"并且該recv()函式回傳 4(正確的長度),但是當我嘗試列印receiveBuffer它時它不起作用。這是輸出:
4 status
h: recv buff
這是客戶端的代碼:
void Client_Connector::Start_Connection()
{
this->sock=socket(AF_INET,SOCK_STREAM,0);
bzero(&this->server,sizeof(server));
this->server.sin_family=AF_INET;
inet_pton(AF_INET,"127.0.0.1", &this->server.sin_addr);
server.sin_port=htons(2500);
int status=connect(sock,(struct sockaddr*) &server, sizeof(server));
if (status==0)
cout<<"Sunteti conectat! \n";
else
Eroare("Eroare de conexiune! Conexiunea nu s-a putut realiza.");
}
void Client_Connector::send_Buffer(char* sendMessage)
{
int i;
i=send(sock, &sendMessage,strlen(sendMessage) 1,0);
cout<<i<<endl;
}
只需呼叫函式:
connecter.Start_Connection();
string sendmsg("Test");
sendmsg ="\0";
connecter.send_Buffer((char*)sendmsg.c_str());
uj5u.com熱心網友回復:
問題是您實際上并沒有發送字串,而是發送指向字串的指標:
i=send(sock, &sendMessage,strlen(sendMessage),0);
這里&sendMessage將是一個指向變數sendMessage的指標,而不是指向字串第一個字符的指標。
簡單的解決方案:
i = send(sock, sendMessage, strlen(sendMessage) 1, 0);
這將發送實際的字串內容,包括終止空字符。
我還建議您退后幾步,重新了解陣列和指標以及相關運算子的知識。
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/344098.html
上一篇:將資訊從AJAX傳遞到控制器類
