[英]sending a .txt file via tcp/ip protocol in c++
我正在嘗試制作一個程序,將一個.txt文件發送到服務器,修改它的內容,然后將修改后的內容發送回C ++中的客戶端。 我已經設法使tcp / ip通信對於簡單的字符串文本消息可以正常工作,但是當我嘗試發送.txt文件的內容時,它無法這樣做。
這是我的代碼的片段:(
客戶:
fstream file;
string fileName = "Test.txt";
string textToSend;
int sendResult;
file.open(fileName);
while (!file.eof())
{
getline(file, textToSend);
sendResult = send(sock, textToSend.c_str(), textToSend.size() + 1, 0);
}
string end_msg = "end";
sendResult = send(sock, end_msg.c_str(), end_msg.size() + 1 , 0);
file.close();
if (sendResult != SOCKET_ERROR)
{
ZeroMemory(buf, 4096);
int bytesReceived = recv(sock, buf, 4096, 0);
if (bytesReceived > 0)
{
cout << "Server> " << string(buf, 0, bytesReceived) << endl;
}
else
{
cout << "Error on client - bytesReceived" << endl;
}
}
// Gracefully close down everything
closesocket(sock);
WSACleanup();
}
服務器:
// While loop: accept and echo message back to client
char buf[4096];
while (true)
{
ZeroMemory(buf, 4096);
// Wait for client to send data
int bytesReceived = recv(clientSocket, buf, 4096, 0);
if (bytesReceived == SOCKET_ERROR)
{
cerr << "Error in recv(). Quitting!" << endl;
break;
}
else
{
if (bytesReceived == 0)
{
cout << "Client disconnected!" << endl;
break;
}
}
buf[bytesReceived] = '\0';
while (buf != "end")
{
cout << buf << endl;
bytesReceived = recv(clientSocket, buf, 4096, 0); //Here seems to be the problem in debug mode
buf[bytesReceived] = '\0';
}
cout << string(buf, 0, bytesReceived) << endl;
// Echo message back to client
send(clientSocket, buf, bytesReceived + 1, 0);
}
// Close socket
closesocket(clientSocket);
// Shutdown Winsocket
WSACleanup();
}
使用調試模式,我注意到在服務器端
bytesReceived = recv(clientSocket, buf, 4096, 0);
它無法到達我的文本文件的第二行。
PS:我是c ++上tcp / ip的新手,具有Java的基本經驗,任何幫助都很好,謝謝。
通常,需要定義某種通信協議才能干凈地發送和接收數據。 特別是如果您發送和接收多條消息。
在這里,數據是從客戶端和服務器發送和接收的,而不考慮其他應用程序處於哪個狀態。
我猜想客戶端可能已關閉連接,服務器無法發送答復,因此它不會繼續接收下一條消息。
我不得不猜測,因為沒有提供整個代碼來進行復制。
您應該進行一些調試-檢查哪種狀態是以太應用程序以及代碼內部發生了什么。 使用兩個IDE-一個用於服務器,一個用於客戶端。
下面是一個簡單的客戶端,它將其信息發送到服務器,服務器剛剛接收到它。
如果需要更復雜的方案,則必須考慮客戶端和服務器之間如何達成共識,如何知道下一步該怎么做。
客戶端和服務器代碼根據MSDN:運行Winsock客戶端和服務器代碼示例
在// Send an initial buffer
,函數應該發送數據並檢查已經發送了多少數據。
像這樣:
std::ifstream file( "Test.txt" );
std::string content( ( std::istreambuf_iterator< char >( file ) ),
( std::istreambuf_iterator< char >() ) );
// Send an initial buffer
int bytes_to_send = content.length();
int bytes_sent = 0;
do
{
iResult = send( ConnectSocket, content.data() + bytes_sent, bytes_to_send, 0 );
if ( iResult != SOCKET_ERROR )
{
bytes_to_send -= iResult;
bytes_sent += iResult;
}
} while ( iResult != SOCKET_ERROR && bytes_to_send > 0 );
在接收方,代碼還必須像示例中那樣循環接收:
// Receive until the peer shuts down the connection
do
{
iResult = recv( ClientSocket, recvbuf, recvbuflen, 0 );
if ( iResult > 0 )
{
//...
} while ( iResult > 0 );
我使用了2MB的測試文件,並且send
命令通過一次發送所有數據來工作。
在接收端,以512字節的批處理接收數據,這意味着該循環存在許多迭代。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.