0

I'm creating a Project in which a C++ Client needs to send a string to a Java Server, via a Socket connection between the two programs. When I run the server and client programs a connection is successfully established between the two. However, when I attempt to send User Input from the C++ program to the Java program, the Java server does not receive the message. I'm relatively new to socket programming so I apologize in advance for any dumb mistakes.

Surprisingly, however, messages sent from the server seem to be received by the client.

Java Server:

public class EchoServer {
    public static void main(String[] args) throws IOException {
    if (args.length < 1) {
        System.err.println("Usage: java EchoServer <port number>");
        System.exit(1);
    }
    System.out.println("Server started. Listening on Port 54000" );
    int portNumber = Integer.parseInt(args[0]);
        try (
        ServerSocket serverSocket = new ServerSocket(portNumber);
        Socket clientSocket = serverSocket.accept();

        PrintWriter out = new 
        PrintWriter(clientSocket.getOutputStream(), true);
        BufferedReader in = new BufferedReader(new 
        InputStreamReader(clientSocket.getInputStream())); ){

        System.out.println("Client connected on port " + portNumber 
        +". Servicing requests.");       
        out.write("CONNECTION ESTABLISHED");
        out.flush();
        String inputLine = "";
          while(true){
          System.out.println("Working");           
          inputLine = in.readLine();
          if(inputLine == ""){
              System.out.println("No Input");

          }else{
              System.out.println(inputLine);
          }
      }
} catch (IOException e) {
    System.out.println("Exception caught when trying to listen on 
    port "
        + portNumber + " or listening for a connection");
    }
}
}

C++ Client:

int main() {

    string ipAddress = "127.0.0.1";         
    int port = 54000;                       
    // Initialize WinSock
    WSAData data;
    WORD ver = MAKEWORD(2, 2);
    int wsResult = WSAStartup(ver, &data);
    if (wsResult != 0)
    {
        cerr << "Can't start Winsock, Err #" << wsResult << endl;
        return 0;
    }
    // Create socket
    SOCKET sock = socket(AF_INET, SOCK_STREAM, 0);
    if (sock == INVALID_SOCKET)
    {
        cerr << "Can't create socket, Err #" << WSAGetLastError() << endl;
        WSACleanup();
        return 0;
    }
    // Fill in a hint structure
    sockaddr_in hint;
    hint.sin_family = AF_INET;
    hint.sin_port = htons(port);
    inet_pton(AF_INET, ipAddress.c_str(), &hint.sin_addr);
    // Connect to server
    int connResult = connect(sock, (sockaddr*)&hint, sizeof(hint));
        if (connResult == SOCKET_ERROR)
        {
            cerr << "Can't connect to server, Err #" << WSAGetLastError() << endl;
            closesocket(sock);
            WSACleanup();
            return 0;
        }
    // Do-while loop to send and receive data
    char buf[4096];
    string userInput;
    do {
        // Prompt the user for some text
        cout << "> ";
        cin >> userInput;

        if (userInput.size() > 0)       // Make sure the user has typed in something
        {
            // Send the text
            int sendResult = send(sock, userInput.c_str(), userInput.size(), 0);
            if (sendResult != SOCKET_ERROR)
            {
                // Wait for response
                ZeroMemory(buf, 4096);
                int bytesReceived = recv(sock, buf, 4096, 0);
                if (bytesReceived > 0)
                {
                    // Echo response to console
                    cout << "SERVER> " << string(buf, 0, bytesReceived) << endl;
                }
            }
        }
    } while (userInput.size() > 0);

    closesocket(sock);
    WSACleanup();
    return 0;
}
Itsleko
  • 25
  • 4
  • 3
    I don't know enough C++ sockets to pinpoint the error but usually the error in these questions is always the same. Wrapping a Java stream in a `BufferedReader` means that `readLine()` will read a ***LINE*** of text. Lines are delineated with a ***NEWLINE*** character. If you never send a newline, the Java side just hangs, wait for the end of line. Either close the socket or send a `\n` to the Java side. – markspace Dec 05 '19 at 23:17
  • 2
    In your Java code, you are comparing strings using `==`: `inputLine == ""`. Compare strings using `equals`, or better yet, check if a string is empty using `isEmpty()`: `if(inputString.isEmpty())` – Vince Dec 05 '19 at 23:56
  • 1
    Unrelated: if you make a simple class that sets up and calls `WSAStartup` and also calls `WSACleanup` in the destructor, and then you waste a few bytes of memory instantiating the class as an automatic variable at the top of `main`, you won't have to litter `WSACleanup`s all through the code. It'll be automatically called when the instance goes out of scope. For more on this trick, read [What is meant by Resource Acquisition is Initialization (RAII)?](https://stackoverflow.com/questions/2321511/what-is-meant-by-resource-acquisition-is-initialization-raii) – user4581301 Dec 06 '19 at 00:02
  • @markspace I realized now that you are correct. I simply needed to append a "\n" to my c++ string and everything works now! Much appreciated! – Itsleko Dec 06 '19 at 14:09

0 Answers0