me_digvijay
me_digvijay

Reputation: 5502

Check the type of data sent/received in java on network

I have a simple java peer-to-peer chat program which works fine. I want to add a feature in this program. I want to enable the users to send files also over the network.

Currently with the simple chatting, I don't have to worry about the type or data that is sent or received/sent by the user. But with the file transfer capability I have to know what type of data (whether a file or plain text) is being sent so that if the its plain text I can simply show it to the user but with the file I have to open a JFilechooser or some kind of dialog box to receive or send the file. The following is the code at the receiving end

try {
        incoming = new BufferedReader(new InputStreamReader(css.getInputStream()));

        String receive = new String();
        String history = "";
        String name = incoming.readLine();
        chatWindow.RemoteField.setText(name);

        do {
            receive = incoming.readLine();
            history = history + "\n" + receive;
            if (receive != null) {
                chatWindow.recm.setText(history);
            } else {
                receive = "BYE";
            }

            //System.out.println("Received Message: "+receive);

        } while (receive.equals("BYE") != true);
    } catch (Exception npe) {
        System.out.println("Error2" + npe);
    }

So how can I add checking of type of data that is received before showing it to the user.

Upvotes: 0

Views: 300

Answers (1)

SimonC
SimonC

Reputation: 6718

You need to send some value that indicates what the next item of data is going to be. For example, you could precede each text line with a value of TEXT\n, and for each file FILE:nnn\n where \n is the newline character and nnn is the file size in bytes, so you know how much of the stream to read before expecting another TEXT or FILE marker.

UPDATE

For example, your incoming stream might look like:

TEXT
Hey mate, here's some cool file
FILE:10
1234
56789TEXT
Did you get it ok?

I'm assuming a chat message will only ever be one line of text. Also, the file doesn't need to be terminated with a line return because the number of bytes is already known, 10 in the example above (including the new line character between 4 and 5). The contents of the file here is:

1234
56789

Upvotes: 2

Related Questions