![](/img/trans.png)
[英]Networking between Java Socket client and C++ (Boost based) server
[英]Cant read with a boost C++ client from a java server
我正在嘗試使用C ++客戶端和Java服務器創建一個簡單的消息傳遞應用程序。
似乎我無法解決問題,因為C ++客戶端無法從Java服務器獲取信息,但是我無法找到問題所在。
我嘗試將Java客戶端連接到Java服務器,並且效果很好。
我嘗試將C ++客戶端連接到為此目的而制作的簡單C ++回顯服務器,並且一切進展順利(它讀取信息)。
我嘗試將Java客戶端連接到C ++回顯服務器,並且效果很好。
請記住,Java服務器從客戶端獲取所有信息,並且正在響應(例如:當我嘗試登錄時,服務器獲取它,登錄我,然后“發送” http響應,以設置cookie並顯示一個歡迎訊息,但客戶永遠無法收到。
這是發送回復的Java代碼:
while ((msg = tokenizer.nextMessage()) != null)
{
System.out.println("Received \"" + msg + "\" from client");
String response = (String)protocol.processMessage(msg);
System.out.println(response); // used for testing
if (response != null)
{
clientSocket.getOutputStream().write(response.getBytes("UTF-8"));
//the Out below this line is being initialized on connection, just put it here for you to read
//Also the out.println(response) doesn't work as well, those are 2 attempts i have made
//out = new PrintWriter(new OutputStreamWriter(clientSocket.getOutputStream(), "UTF-8"), true);
//out.println(response);
}
if (protocol.isEnd(msg))
{
break;
}
}
這是客戶端代碼(C ++):
//while (_socket.available() == 0){
// boost::this_thread::sleep(boost::posix_time::milliseconds(10));
// std::cout << "test";
//}
char reply[max_length];
size_t reply_length = boost::asio::read(_socket,boost::asio::buffer(reply,10));
//size_t reply_length = boost::asio::read(_socket, boost::asio::buffer(reply, _socket.available()));
std::cout << "Reply is:\n";
std::cout.write(reply, reply_length);
std::cout << "\n";
請注意,上面代碼中的while用來等待每條發送的消息后的響應,我嘗試將其替換為更長的睡眠時間,這樣就不必檢查傳入緩沖區的大小,因為可以在測試之后立即看到,我正嘗試從測試中讀取大小為10的緩沖區,然后將“真實”讀取行放在它后面的注釋中。
任何幫助,將不勝感激。
謝謝。
編輯-忘了提一下,如果我在發送信息傳遞后關閉了套接字,但是這樣做沒有達到目的,因為我試圖保持套接字打開,直到客戶端執行注銷。
編輯#2-我嘗試了一種不同的讀取方法,通過使用定界符char並在此時獲得1個char緩沖區,它只是被空緩沖區卡住了。
這是我嘗試的第二種閱讀類型的代碼:
std::string respone = "";
char ch='0';
boost::system::error_code error;
try {
while(!error && ch!='$'){
size_t tmp=0;
try {
std::cout << "going to read:";
tmp = _socket.read_some(boost::asio::buffer(&ch + tmp, 1 - tmp), error);
std::cout << "finish reading 1 char";
if (error)
throw boost::system::system_error(error);
}
catch (std::exception& e) {
std::cerr << "recv failed (Error: " << e.what() << ')' << std::endl;
}
respone.append(1, ch);
}
}
有點愚蠢,但顯然我的防病毒軟件阻止了來自Java服務器的所有數據包(出於某種原因而不是c ++),將其關閉可以解決所有問題。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.