【问题标题】:Cannot get ObjectInputStream to work无法让 ObjectInputStream 工作
【发布时间】:2012-03-22 16:13:54
【问题描述】:

我目前正在尝试让我的服务器与客户端建立连接。我为每个连接创建了一个线程,但服务器当前没有创建输入流。我已经通过打印数字进行了测试,但只有 1 和 2 被打印出来。我确定这只是我缺少的一个小问题。

public class ObjectHandler implements Runnable{
    Socket sock;
    ObjectInputStream ois;
    ObjectOutputStream oops;
    InputStream is;


    public ObjectHandler(Socket clientSocket) throws IOException {
        System.out.println("1");
        sock = clientSocket;

        is = sock.getInputStream();
        System.out.println("2");
        ois = new ObjectInputStream(new BufferedInputStream(is));
        System.out.println("3");

        OutputStream os = sock.getOutputStream();

        oops = new ObjectOutputStream(new BufferedOutputStream(os));
        outputSockets.add(oops);    

    }

我现在已经删除了 throws IOException 并用 try catch 包围了读者。客户端崩溃后,它现在会打印此错误:

at java.io.ObjectInputStream$PeekInputStream.readFully(ObjectInputStream.java:2280)
at java.io.ObjectInputStream$BlockDataInputStream.readShort(ObjectInputStream.java:2749)
at java.io.ObjectInputStream.readStreamHeader(ObjectInputStream.java:779)
at java.io.ObjectInputStream.<init>(ObjectInputStream.java:279)
at ThreadPool$ObjectHandler.<init>(ThreadPool.java:95)
at ThreadPool.addThread(ThreadPool.java:31)
at ObjectServerTest.go(ObjectServerTest.java:93)
at ObjectServerTest.main(ObjectServerTest.java:124)

【问题讨论】:

  • 您遇到异常了吗?你能给我们堆栈跟踪吗?
  • 这只是堆栈跟踪的一部分。我们需要看到这一切。

标签: java sockets stream network-programming


【解决方案1】:

在通过套接字构造对象流时,总是需要首先构造输出流并在创建输入流之前刷新它(由于流是如何实现的)。

【讨论】:

    【解决方案2】:

    删除BufferedInputStream。你不需要它。它一直在等待读取 4K 字节。

    编辑: 也删除BufferedOutputStream。 并确保您在客户端刷新输出流。

    【讨论】:

    • 创建缓冲输入流不会触发读取。更重要的是,从缓冲的输入流中读取数据不需要在返回值之前读取 4k 字节的数据。
    【解决方案3】:

    这对我有用...

    对象处理程序:

    public ObjectHandler(Socket clientSocket) throws IOException {
        System.out.println("1");
        sock = clientSocket;
    }
    
    
    @Override
    public void run() {
        try {
            is = sock.getInputStream();
            System.out.println("2");
            ois = new ObjectInputStream(new BufferedInputStream(is));
            System.out.println("3"+ois.readFloat());
    
            OutputStream os = sock.getOutputStream();
    
            oops = new ObjectOutputStream(new BufferedOutputStream(os)); 
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    

    客户:

    public static void main(String[] args) throws UnknownHostException, IOException {
        Socket client = new Socket(InetAddress.getByName("localhost"), 8888);
        OutputStream os = client.getOutputStream();
        ObjectOutputStream oos = new ObjectOutputStream(os);
        oos.writeFloat(new Float(10.10));
        oos.flush();
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-01-12
      • 1970-01-01
      • 1970-01-01
      • 2020-02-23
      • 2014-12-26
      • 2017-12-22
      • 2012-02-28
      • 2015-12-01
      相关资源
      最近更新 更多