简体   繁体   中英

Java networking Not Working

Im trying to solve an exercise on JAVA IO . The problem i get is that the messages are not coming on the correct order. For example this is what happens:

  1. Run server

  2. Run Client

  3. Type Password

  4. Two

  5. Three

  6. Wrong password

  7. One

  8. Wrong password

  9. Trial

  10. Waiting for sentence

  11. T

  12. TRIAL

Your IP address is :/
Your Socket is : 4351
Current date is : 2011/05/18 15:45:13.
So for some reason the messeges are not on right order. This is the code:

import java.io.*;
import java.net.*;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;


class TCPServer {

    public TCPServer() {
    }

    public static void main(String args[])
            throws Exception {
        String clientSentence;
        String capitalisedSentence;
        DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
        Date date = new Date();

        ServerSocket welcomeSocket = new ServerSocket(4351);

        while (true) {

            Socket clientSocket = welcomeSocket.accept();
            BufferedReader inFromClient =
                    new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
            DataOutputStream outToClient =
                    new DataOutputStream(clientSocket.getOutputStream());

            boolean correctPass = false;
            while (!correctPass) {
                if (getPassword(clientSocket,inFromClient,outToClient)) {
                    correctPass = true;
                }
            }


            outToClient.writeBytes("Waiting for sentence"+"\n"); 

            clientSentence = inFromClient.readLine();

            capitalisedSentence = clientSentence.toUpperCase();

            outToClient.writeBytes(capitalisedSentence + "\n"
                    + "Your IP address is :" + clientSocket.getInetAddress() + "\n"
                    + "Your Socket is : " + clientSocket.getLocalPort() + "\n"
                    + "Current date is : " + dateFormat.format(date) + "\n");

        }
    }

    private static boolean getPassword(Socket clientSocket,BufferedReader inFromClient,DataOutputStream outToClient) throws Exception {
        boolean passed = false;
        outToClient.writeBytes("Type password." + "\n");
        while (!passed) {
            String password = inFromClient.readLine();
            if (password.equals("1")) {
                passed = true;

            } else {
                outToClient.writeBytes("Wrong Password" + "\n");
            }

        }
        return true;
    }
}

import java.io.*;
import java.net.*;


class TCPClient {

    public static void main(String args[])
            throws Exception {
        String sentence;
        String modifiedSentence = "";


        BufferedReader inFromUser =
                new BufferedReader(new InputStreamReader(System.in));


        Socket clientSocket = new Socket("localhost", 4351);

        DataOutputStream outToServer =
                new DataOutputStream(clientSocket.getOutputStream());

        BufferedReader inFromServer =
                new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));

        do{
        while(inFromServer.ready()){
            System.out.println(inFromServer.readLine());
        }
        sentence = inFromUser.readLine();
        outToServer.writeBytes(sentence + "\n");


        }while(true);

        // close the socket and the connection
    }
}

the problem is you are using a DataOutputStream for output and a Reader for input -- instead try using a PrintWriter (which offers a println!) for output and the Reader you currently use for reading. It's not a good idea to mix a Stream and a Reader/Writer!

Note that the messages aren't so much in the wrong order, as that you are one behind on the replies from the server. I think your problem is just that you send a message, and then immediately go back to the top of the loop and check if there is an incoming message. If it is not there immediately, you ask for another input. But what if the server does not reply in between the time when you send the message and go back to the top of the loop? This will happen in a nanosecond.

So you're asking a question, and then if you don't get an immediate reply, you're promptly asking another question. Then you display the reply to the first question and ask the third question. Etc. You need to be a little more patient. It's been a while since I've done socket programming, but I think you really need to wait for a reply, don't just say that if there is no reply, barrel ahead.

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