第一個問題:我在TCP中的緩衝區之間感到困惑。我試圖解釋我的問題,我閱讀了這個文檔TCP Buffer,作者說了很多關於TCP緩衝區,這對於初學者來說很好,並且是一個很好的解釋。我需要知道的是,這個TCP緩衝區與我們在基本客戶服務器程序(Char *buffer[Some_Size]
)中使用的緩衝區是相同的緩衝區,還是由TCP內部持有的一些不同的緩衝區。TCP中的垃圾值和緩衝區差異
我第二個問題的是,我從客戶端通過套接字發送帶有前綴長度(This is data From me
)的字符串數據到服務器,當我在控制檯打印我的數據我串沿着它打印一些垃圾值也是這樣"This is data From me zzzzzz 1/2 1/2....."
?。不過,我通過右移char *recvbuf = new char[nlength>>3];
nlength到3位來修復它但爲什麼我需要這樣做?
我第三個問題與第一個問題相關,如果有沒有像TCP緩衝和它的只有約Char *buffer[some_size]
然後什麼區別我的程序會使用這樣的靜態內存分配緩衝注意到,通過使用動態內存分配緩衝區使用char *recvbuf = new char[nlength];
。總之這是最好的,爲什麼?
客戶端代碼
int bytesSent;
int bytesRecv = SOCKET_ERROR;
char sendbuf[200] = "This is data From me";
int nBytes = 200, nLeft, idx;
nLeft = nBytes;
idx = 0;
uint32_t varSize = strlen (sendbuf);
bytesSent = send(ConnectSocket,(char*)&varSize, 4, 0);
assert (bytesSent == sizeof (uint32_t));
std::cout<<"length information is in:"<<bytesSent<<"bytes"<<std::endl;
// code to make sure all data has been sent
while (nLeft > 0)
{
bytesSent = send(ConnectSocket, &sendbuf[idx], nLeft, 0);
if (bytesSent == SOCKET_ERROR)
{
std::cerr<<"send() error: " << WSAGetLastError() <<std::endl;
break;
}
nLeft -= bytesSent;
idx += bytesSent;
}
std::cout<<"Client: Bytes sent:"<< bytesSent;
Server代碼:
int bytesSent;
char sendbuf[200] = "This string is a test data from server";
int bytesRecv;
int idx = 0;
uint32_t nlength;
int length_received = recv(m_socket,(char*)&nlength, 4, 0);//Data length info
char *recvbuf = new char[nlength];//dynamic memory allocation based on data length info
//code to make sure all data has been received
while (nlength > 0)
{
bytesRecv = recv(m_socket, &recvbuf[idx], nlength, 0);
if (bytesRecv == SOCKET_ERROR)
{
std::cerr<<"recv() error: " << WSAGetLastError() <<std::endl;
break;
}
idx += bytesRecv;
nlength -= bytesRecv;
}
cout<<"Server: Received complete data is:"<< recvbuf<<std::endl;
cout<<"Server: Received bytes are"<<bytesRecv<<std::endl;
WSACleanup();
system("pause");
delete[] recvbuf;
return 0;
}
檢查['ntohl()','htonl()'](http://stackoverflow.com/questions/14173441/what-does-ntohluint32-t-do)正確管理消息長度前綴。 –
我知道他們(ntohl和htonl()),但我真的需要他們,因爲我的客戶端服務器在相同的Windows架構。不是嗎? – User
他們沒有必要在同一臺主機上運行這些東西,但網絡編程的目的通常是在不同主機之間交換數據。 –