简体   繁体   中英

Sending multiple strings over same TCP connection in Java?

I have been trying for hours and I just can't seem to get it done. I want to send two strings from TCP client to server, and return them both capitalized. The two strings are username and password: Client code is:

public void actionPerformed(ActionEvent e) {
            final String s1 =textPane.getText();  //retrieve username
            final String s2=passwordField.getText();//retrieve password         
            //**************************************************************************
            //after we have gotten the credentials, we have to send them to the server to check in the database
            Socket clientSocket = null; //create new socket
            String response=null; //create what is supposed to become the server's response
            String response2=null;
            try {
                /**
                 * construct the client socket, specify the IP address which is here
                 * localhost for the loopback device and the port number at which a
                 * connection needs to be initialized.
                 */
                clientSocket = new Socket("localhost", 6789);
                // These streams are for the same purpose as in the server side //
                DataOutputStream outToServer = new DataOutputStream(clientSocket
                        .getOutputStream());
                DataOutputStream outToServer2 = new DataOutputStream(clientSocket
                        .getOutputStream());

                BufferedReader inFromServer = new BufferedReader(
                        new InputStreamReader(clientSocket.getInputStream()));
                // read the user's input from the console. //

                // send the sentence to the server: note the need to append it with
                // an endline character //
                outToServer.writeBytes(s1 + '\n'); //send username
                outToServer.writeBytes(s2 + '\n'); //send password
                // listen on the socket and read the reply of the server //
                response2=inFromServer.readLine();
                response = inFromServer.readLine();

            } catch (UnknownHostException ex) {// catch the exceptions //
                ex.printStackTrace();
            } catch (IOException ex) {
                ex.printStackTrace();
            }
            System.out.println("FROM SERVER: " + response); //print the response of the server
            System.out.println("FROM SERVER: " + response2);
            try {
                // close the socket when done //
                clientSocket.close();
            } catch (IOException ex) {
                ex.printStackTrace();
            }

        }
    });

Bulk of Server Code is:

  while(true) {
        // connection socket //
        Socket connectionSocket;
        try {
            // accept connection on the connection socket from the welcome socket which is a server socket //
            connectionSocket = welcomeSocket.accept();
            // Get the input stream from the connection socket and save it in a buffer //
            BufferedReader inFromClient = new BufferedReader(new InputStreamReader(connectionSocket.getInputStream()));
            // Allocate an output stream to send data back to the client //
            DataOutputStream  outToClient = new DataOutputStream(connectionSocket.getOutputStream());
            // Read the client sentence from the receive buffer //
            clientSentence = inFromClient.readLine();
            clientSentence2=inFromClient.readLine();

            System.out.println("From user: " + clientSentence);
            // capitalize the client's sentence, here the server does actions on the client's data //
            capitalizedSentence = clientSentence.toUpperCase() + '\n';
           capitalizedSentence2=clientSentence2.toUpperCase()+'\n';

            if(clientSentence.equalsIgnoreCase("QUIT")){// close the socket if the server sends a quit message //
               connectionSocket.close();
               System.out.println("Connection Socket Quitting");
               // Note that here the server will not exit or end up it will just close the connection with the client //
            } 
            else outToClient.writeBytes(capitalizedSentence);// Send the capitalized sentence back to the client //
        } catch (IOException ex) {
            ex.printStackTrace();
        }

    }

What am I doing wrong? Can't one buffered reader accept two separate strings? How do I separate them later?

You haven't written back capitalizedSentence2 back to client that's why client is waiting at second readLine() as mentioned below:

        response2 = inFromServer.readLine();
        response = inFromServer.readLine();

put below line in your server side code in else part

 outToClient.writeBytes(capitalizedSentence2);

It might solve your problem.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM