简体   繁体   中英

Problems with socket outputstream and inputstream

I'm trying to develop client-server connection between phone and pc using sockets. During the developing i met a problem and cannnot fix it yet. The problem is with outputstream. I use an ObjectoutputStream to send a String array to client and it works when I use this code:

try
    {
        // отправка пакета с файлами
        DataInputStream dir = new DataInputStream(conn.getInputStream());
        OutputStream dos = conn.getOutputStream();
        ObjectOutputStream objectOutput = new ObjectOutputStream(dos);
        byte messageType = dir.readByte();
        switch(messageType) {
        case 1:
            try {
                textArea.append("\nClient sends a command: " + dir.readUTF());
                objectOutput.writeObject(results);
                objectOutput.close();
            } catch(Exception e) {
                e.printStackTrace();
            }
        }               
        dir.close();
    } catch (IOException e) {
        ......

but when I move ObjectOutputStream to the switcher:

try
    {
        // отправка пакета с файлами
        DataInputStream dir = new DataInputStream(conn.getInputStream());
        OutputStream dos = conn.getOutputStream();
        byte messageType = dir.readByte();
        switch(messageType) {
        case 1:
            try {
                ObjectOutputStream objectOutput = new ObjectOutputStream(dos);
                textArea.append("\nClient sends a command: " + dir.readUTF());
                objectOutput.writeObject(results);
                objectOutput.close();
            } catch(Exception e) {
                e.printStackTrace();
            }
        }               
        dir.close();
    } catch (IOException e) {
        ....

my program freezes. I need to do like this, because i also need to do another commands, like sending and receiving files. Any solutions for this problem?

I've solved a problem. I just use BufferedReader & Writer for it, because it will be also used for transferring files. So now code works fine and looks like this:

// отправка пакета с файлами
            BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream()));
            BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(conn.getOutputStream(), ENCODING));
            String messageType = br.readLine();
            switch(messageType) {
            case "connect": {
                List<String> results = new ArrayList<String>();

                File[] files = new File("C:/Tenzor_Denis/ServerFiles/").listFiles();
                //If this pathname does not denote a directory, then listFiles() returns null. 

                for (File file : files) {
                    if (file.toString().endsWith(".txt")) {
                        results.add(file.getName());
                    }
                }

                try {
                    for(int i = 0; i < results.size(); i++) {
                        bw.write(results.get(i));
                        bw.newLine();
                        //textArea.append(" " + results.get(i));
                    }
                    textArea.append("\nClient sends a command: " + messageType);

                } catch(Exception e) {
                    e.printStackTrace();
                }
                bw.close();
                br.close();
            }
            break;
            }
        }

Thx to all for answers.

Which line does it freeze on? It seems like reading from the input stream causes the output stream to block until everything is consumed. Look at the documentation for your conn object. What class is this? Perhaps moving the dir.readUTF() call before creating the ObjectOutputStream might solve it.

You can't do it either way. Closing the ObjectOutputStream will close the socket. You need to keep it open for the life of the socket. So moving it inside the case is futile anyway.

But your code doesn't make sense. You're writing with ObjectOutputStream, yet all you're reading from the peer is a single byte. If you're writing objects, you need to read objects, with an ObjectInputStream, not a DataInputStream, and when using both object input and output streams you must always construct the ObjectOutputStream first, at both ends to be safe.

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