Search code examples
javac++swingsocketsserversocket

Socket [C++\Java] The ServerSocket receives a string only when the client closes


I've a application in C++ that will run on Linux. I created with Java a log GUI (choose Java because I've already worked with this language and Java swing). In a nutshell, the GUI creates a ServerSocket, my Application uses the log service as a client and send the log via the network to the server.

My problem is, as the title says, all the data are received when I close the client (stop it from Eclipse).

These are my pieces of code:

Server Side [Java]

ServerSocket serverSocket = new ServerSocket(3000);
System.out.println("ServerSocket created");
Socket socket = serverSocket.accept();
System.out.println("Connection received");
if (socket != null)
{
    java.io.InputStream is = socket.getInputStream();
    java.io.InputStreamReader isr = new java.io.InputStreamReader(is);
    BufferedReader br = new BufferedReader(isr);
    String a;
    do
    {
        a = br.readLine();
        System.out.println(a + " received");
    }
    while (a != null);
}

Client Side [C++]

while(true)
{
    std::unique_lock<std::mutex> lock {_mutex};
    _isLogEmpty.wait(lock,
                     [&]{return !_logs.empty();});
    try
    {
        std::string logToSend = _logs.front();
        char* messageToSendAsChar = new char[logToSend.length()+1];
        strcpy(messageToSendAsChar, logToSend.c_str());

        if (write(_fileDescriptor, messageToSendAsChar, logToSend.length()+1) > 0)
        {
            _logs.pop();
            logToSend.clear();
        }

        delete[] messageToSendAsChar;
    }
    catch (std::exception &e)
    {

    }
    catch (...)
    {

    }
}

Any help will be appreciated. Thank you!


Solution

  • I would guess that the char arrays you send from the C++ application do not contain

    a line feed ('\n'), a carriage return ('\r'), or a carriage return followed immediately by a linefeed.

    BufferedReader.readLine() (Java Platform SE 7).

    Then by closing the C++-client (thus closing the socket) the readLine method may return.

    (Sorry for posting this as answer, but until now i am not allowed to post comments to questions directly)