如何在写入ObjectOutputStream后读取套接字响应?

时间:2016-01-20 14:33:30

标签: java sockets

我正在使用Socket将任务从一台服务器发送到另一台服务器,如下所示:

private boolean sendRequest(String address, int port) {
    boolean requestComplete = false;
    try {
        Socket socket = new Socket(address, port);
        ObjectOutputStream oos = new ObjectOutputStream(socket.getOutputStream());
        oos.writeObject("task_to_complete");

        ObjectInputStream ois = new ObjectInputStream(socket.getInputStream());
        String msg = (String)ois.readObject();
        if(msg.equals("complete")){
            requestComplete = true;
        }
        ois.close();
        oos.close();
        socket.close();
    } catch (Exception e) {
        e.printStackTrace();
    }
    return requestComplete;
}

第二台服务器接收如下任务:

while (true) {

    // wait for connection
    Socket socket = serverSocket.accept();
    System.out.println("New connection accepted " + socket.getInetAddress() + ":" + socket.getPort());

    // retrieve request from server
    ObjectInputStream ois = new ObjectInputStream(socket.getInputStream());
    String msg = (String) ois.readObject();

    switch (msg) {
    case "task_to_complete":
        // do task 1
        break;
    }

    System.out.println("Task " + msg + " complete.");

    // send a message back to client with the result of the task it
    // requested
    PrintWriter out =
            new PrintWriter(socket.getOutputStream(), true);
        out.print("complete");
    ois.close();
    socket.close();
}

但是我收到了错误

  

java.io.EOFException at   java.io.ObjectInputStream $ PeekInputStream.readFully(未知来源)

当我尝试阅读消息"完成"从第一台服务器: ObjectInputStream ois = new ObjectInputStream(socket.getInputStream());

导致此错误的原因是什么?

2 个答案:

答案 0 :(得分:2)

你弄乱了你的协议,因为

  • 服务器使用PrintWriter.print("completed")
  • 写回复
  • 客户端使用readObject()
  • 读取它

我放了working demo on GitHub

答案 1 :(得分:0)

尝试使用

public static String getPath(final Context context, final Uri uri) {

    final boolean isKitKat = Build.VERSION.SDK_INT >=
                             Build.VERSION_CODES.KITKAT;
    Log.i("URI",uri+"");
    String result = uri+"";

    // DocumentProvider
    // if (isKitKat && DocumentsContract.isDocumentUri(context, uri)) {
    if (isKitKat && (result.contains("media.documents"))) {

        String[] ary = result.split("/");
        int length = ary.length;
        String imgary = ary[length-1];
        final String[] dat = imgary.split("%3A");

        final String docId = dat[1];
        final String type = dat[0];

        Uri contentUri = null;
        if ("image".equals(type)) {
            contentUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
        }
        else if ("video".equals(type)) {
        }
        else if ("audio".equals(type)) {
        }

        final String selection = "_id=?";
        final String[] selectionArgs = new String[] {
            dat[1]
        };

        return getDataColumn(context, contentUri, selection, selectionArgs);
    }
    else
    if ("content".equalsIgnoreCase(uri.getScheme())) {
        return getDataColumn(context, uri, null, null);
    }
    // File
    else if ("file".equalsIgnoreCase(uri.getScheme())) {
        return uri.getPath();
    }

    return null;
}

public static String getDataColumn(Context context, Uri uri, String selection,
                                   String[] selectionArgs) {
    Cursor cursor = null;
    final String column = "_data";
    final String[] projection = {
            column
    };

    try {
        cursor = context.getContentResolver().query(uri, projection, selection, selectionArgs,
                null);
        if (cursor != null && cursor.moveToFirst()) {
            final int column_index = cursor.getColumnIndexOrThrow(column);
            return cursor.getString(column_index);
        }
    }
    finally {
        if (cursor != null)
            cursor.close();
    }
    return null;
}

在类似情况下它对我有用