客户端 - 服务器 - 客户端文件传输问题(NIO)

时间:2016-09-21 16:03:30

标签: java io server client-server nio

美好的一天,团队,

我有一个文件传输应用程序,它通过服务器从客户端1向客户端2发送文件。在发送i分割文件然后逐个传输之前(每件2048字节)。一切都运行正常,但不幸的是有时候我有2个错误,我无法管理,有些文件因为它没有转移。发生错误时,我没有看到任何关系。它只发生在服务器端。增加客户端对服务器的请求之间的延迟并没有帮助。

下面的错误和服务器代码。

提前致谢。

服务器代码:

import ClientServer.model.Envelope;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.*;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.util.Iterator;
import java.util.Set;

public class Server {
    public static Logger logger = LoggerFactory.getLogger(Server.class);

    public static void main(String[] args) {
        try {
            transfer();
        } catch (IOException e) {
            logger.error(e.getMessage());
        }
    }

    public static void transfer() throws IOException {
        String status = "sender";
        SocketChannel socketChannel;
        Envelope envelopeToTransfer = new Envelope();
        ByteBuffer byteBuffer = null;
        ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();
        serverSocketChannel.configureBlocking(false);
        InetSocketAddress inetSocketAddress = new InetSocketAddress(1883);
        serverSocketChannel.socket().bind(inetSocketAddress);
        Selector selector = Selector.open();
        int ops = serverSocketChannel.validOps();
        serverSocketChannel.register(selector, ops, null);
        while (true) {
            selector.select();
            Set<SelectionKey> selectionKeySet = selector.selectedKeys();
            Iterator<SelectionKey> selectionKeyIterator = selectionKeySet.iterator();
            while (selectionKeyIterator.hasNext()) {
                SelectionKey key = selectionKeyIterator.next();
                selectionKeyIterator.remove();
                if (key.isAcceptable()) {
                    socketChannel = serverSocketChannel.accept();
                    socketChannel.configureBlocking(false);
                    socketChannel.register(selector, SelectionKey.OP_READ);
                    byteBuffer = ByteBuffer.allocate(8096);
                    continue;
                } else if (key.isReadable()) {
                    socketChannel = (SocketChannel) key.channel();
                    byteBuffer.clear();
                    try {
                        socketChannel.read(byteBuffer);
                    } catch (Exception e) {
                        logger.error(e.getMessage());
                        socketChannel.close();
                        continue;
                    }
                    Envelope envelope;
                    try {
                        envelope = (Envelope) deserialize(byteBuffer.array());
                        byteBuffer.clear();
                    } catch (Exception e) {
                        logger.error(e.getMessage());
                        e.printStackTrace();
                        socketChannel.close();
                        continue;
                    }
                    if (envelope.userType.equals("sender") & status.equals("sender")) {
                        envelopeToTransfer = envelope;
                        if (envelope.fileTransferRequest.equals("Yes")) {
                            Envelope envelopeAnswer = new Envelope();
                            envelopeAnswer.fileTransferAnswer = "Approved";
                            byteBuffer = ByteBuffer.wrap(serialize(envelopeAnswer));
                            socketChannel.write(byteBuffer);
                        }
                        status = "receiver";
                        continue;
                    } else if (envelope.userType.equals("receiver") & status.equals("receiver")) {
                        try {
                            if (envelopeToTransfer.clientIdentifier.equals(envelope.userIdentifier)) {
                                byteBuffer.clear();
                                byteBuffer = ByteBuffer.wrap(serialize(envelopeToTransfer));
                                logger.info(envelopeToTransfer.nameOfTransferedFile);
                                socketChannel.write(byteBuffer);
                                status = "sender";
                                continue;
                            }
                        } catch (Exception e) {
                            logger.error(e.getMessage());
                            continue;
                        }
                    }
                }
            }
        }
    }

    public static byte[] serialize(Object obj) throws IOException {
        ByteArrayOutputStream b = new ByteArrayOutputStream();
        ObjectOutputStream o = new ObjectOutputStream(b);
        b.flush();
        o.flush();
        o.writeObject(obj);
        return b.toByteArray();
    }

    public static Object deserialize(byte[] bytes) throws IOException, ClassNotFoundException {
        ByteArrayInputStream b = new ByteArrayInputStream(bytes);
        ObjectInputStream o = new ObjectInputStream(b);
        return o.readObject();
    }

}

错误1:

java.io.EOFException
    at java.io.ObjectInputStream$PeekInputStream.readFully(ObjectInputStream.java:2353)
    at java.io.ObjectInputStream$BlockDataInputStream.readUTFBody(ObjectInputStream.java:3092)
    at java.io.ObjectInputStream$BlockDataInputStream.readUTF(ObjectInputStream.java:2892)
    at java.io.ObjectInputStream.readString(ObjectInputStream.java:1646)
    at java.io.ObjectInputStream.readObject0(ObjectInputStream.java:1344)
    at java.io.ObjectInputStream.defaultReadFields(ObjectInputStream.java:2018)
    at java.io.ObjectInputStream.readSerialData(ObjectInputStream.java:1942)
    at java.io.ObjectInputStream.readOrdinaryObject(ObjectInputStream.java:1808)
    at java.io.ObjectInputStream.readObject0(ObjectInputStream.java:1353)
    at java.io.ObjectInputStream.readObject(ObjectInputStream.java:373)
    at Server.src.Server.deserialize(Server.java:115)
    at Server.src.Server.transfer(Server.java:65)
    at Server.src.Server.main(Server.java:22)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at com.intellij.rt.execution.application.AppMain.main(AppMain.java:144)

错误2:

java.io.StreamCorruptedException: invalid type code: 00
    at java.io.ObjectInputStream.readObject0(ObjectInputStream.java:1381)
    at java.io.ObjectInputStream.defaultReadFields(ObjectInputStream.java:2018)
    at java.io.ObjectInputStream.readSerialData(ObjectInputStream.java:1942)
    at java.io.ObjectInputStream.readOrdinaryObject(ObjectInputStream.java:1808)
    at java.io.ObjectInputStream.readObject0(ObjectInputStream.java:1353)
    at java.io.ObjectInputStream.readObject(ObjectInputStream.java:373)
    at Server.src.Server.deserialize(Server.java:115)
    at Server.src.Server.transfer(Server.java:65)
    at Server.src.Server.main(Server.java:22)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at com.intellij.rt.execution.application.AppMain.main(AppMain.java:144)

0 个答案:

没有答案